Programs & Examples On #Color mapping

A color map is used when displaying intensity images (2D arrays). The color maps intensity values to RGB colors of the display.

How to convert a NumPy array to PIL image applying matplotlib colormap

  • input = numpy_image
  • np.unit8 -> converts to integers
  • convert('RGB') -> converts to RGB
  • Image.fromarray -> returns an image object

    from PIL import Image
    import numpy as np
    
    PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
    
    PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
    

Determine whether an array contains a value

This is generally what the indexOf() method is for. You would say:

return arrValues.indexOf('Sam') > -1

Checking for multiple conditions using "when" on single task in ansible

You can use like this.

when: condition1 == "condition1" or condition2 == "condition2"

Link to official docs: The When Statement.

Also Please refer to this gist: https://gist.github.com/marcusphi/6791404

Android: adb: Permission Denied

Run your cmd as administrator this will solve my issues. Thanks.

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

Loading context in Spring using web.xml

You can also load the context while defining the servlet itself (WebApplicationContext)

  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/*.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

rather than (ApplicationContext)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

or can do both together.

Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet etc)

Context loaded by ContextLoaderListener will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

Cross-reference (named anchor) in markdown

For anyone who is looking for a solution to this problem in GitBook. This is how I made it work (in GitBook). You need to tag your header explicitly, like this:

# My Anchored Heading {#my-anchor}

Then link to this anchor like this

[link to my anchored heading](#my-anchor)

Solution, and additional examples, may be found here: https://seadude.gitbooks.io/learn-gitbook/

How to display 3 buttons on the same line in css

This will serve the purpose. There is no need for any divs or paragraph. If you want the spaces between them to be specified, use margin-left or margin-right in the css classes.

<div style="width:500px;">
    <button type="submit" class="msgBtn" onClick="return false;" >Save</button>
    <button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
    <button class="msgBtnBack">Back</button>
</div> 

How to remove components created with Angular-CLI

There's the --dry-run flag which will allow you to preview the changes, and/or you can use the Angular Console App to generate the cli flags for you, using their easy GUI. It auto-previews everything before you commit to it.

IPC performance: Named Pipe vs Socket

As often, numbers says more than feeling, here are some data: Pipe vs Unix Socket Performance (opendmx.net).

This benchmark shows a difference of about 12 to 15% faster speed for pipes.

Convert integers to strings to create output filenames at run time

Well here is a simple function which will return the left justified string version of an integer:

character(len=20) function str(k)
!   "Convert an integer to string."
    integer, intent(in) :: k
    write (str, *) k
    str = adjustl(str)
end function str

And here is a test code:

program x
integer :: i
do i=1, 100
    open(11, file='Output'//trim(str(i))//'.txt')
    write (11, *) i
    close (11)
end do
end program x

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

How do I get the localhost name in PowerShell?

hostname also works just fine in Powershell

Force div element to stay in same place, when page is scrolled

Change position:absolute to position:fixed;.

Example can be found in this jsFiddle.

A process crashed in windows .. Crash dump location

Windows 7, 64 bit, no modifications to the Registry key, the location is:

C:\Users[Current User when app crashed]\AppData\Local\Microsoft\Windows\WER\ReportArchive

How could I create a list in c++?

We are already in 21st century!! Don't try to implement the already existing data structures. Try to use the existing data structures.

Use STL or Boost library

__init__ and arguments in Python

Every method needs to accept one argument: The instance itself (or the class if it is a static method).

Read more about classes in Python.

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Using `date` command to get previous, current and next month

the following will do:

date -d "$(date +%Y-%m-1) -1 month" +%-m
date -d "$(date +%Y-%m-1) 0 month" +%-m
date -d "$(date +%Y-%m-1) 1 month" +%-m

or as you need:

LAST_MONTH=`date -d "$(date +%Y-%m-1) -1 month" +%-m`
NEXT_MONTH=`date -d "$(date +%Y-%m-1) 1 month" +%-m`
THIS_MONTH=`date -d "$(date +%Y-%m-1) 0 month" +%-m`

you asked for output like 9,10,11, so I used the %-m

%m (without -) will produce output like 09,... (leading zero)

this also works for more/less than 12 months:

date -d "$(date +%Y-%m-1) -13 month" +%-m

just try

date -d "$(date +%Y-%m-1) -13 month"

to see full result

Execute raw SQL using Doctrine 2

//$sql - sql statement
//$em - entity manager

$em->getConnection()->exec( $sql );

How to count instances of character in SQL Column

Here's what I used in Oracle SQL to see if someone was passing a correctly formatted phone number:

WHERE REPLACE(TRANSLATE('555-555-1212','0123456789-','00000000000'),'0','') IS NULL AND
LENGTH(REPLACE(TRANSLATE('555-555-1212','0123456789','0000000000'),'0','')) = 2

The first part checks to see if the phone number has only numbers and the hyphen and the second part checks to see that the phone number has only two hyphens.

Android: remove notification from notification bar

simply set setAutoCancel(True) like the following code:

Intent resultIntent = new Intent(GameLevelsActivity.this, NotificationReceiverActivityAdv.class);

PendingIntent resultPendingIntent =
        PendingIntent.getActivity(
                GameLevelsActivity.this,
                0,
                resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
                );

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
        getApplicationContext()).setSmallIcon(R.drawable.icon)
        .setContentTitle(adv_title)
        .setContentText(adv_desc)
        .setContentIntent(resultPendingIntent)
         //HERE IS WHAT YOY NEED:
        .setAutoCancel(true);

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(547, mBuilder.build());`

How to detect the OS from a Bash script?

The bash manpage says that the variable OSTYPE stores the name of the operation system:

OSTYPE Automatically set to a string that describes the operating system on which bash is executing. The default is system- dependent.

It is set to linux-gnu here. jio

What Java FTP client library should I use?

I was downloading video files. Apache's FTPClient fumbled, it downloaded the video reasonably fast. but when I tried to play the video back, it lost chunks out of the middle of the video. ftp4j would download the whole video with no loss.

ftp4j ftw

Shared-memory objects in multiprocessing

Like Robert Nishihara mentioned, Apache Arrow makes this easy, specifically with the Plasma in-memory object store, which is what Ray is built on.

I made brain-plasma specifically for this reason - fast loading and reloading of big objects in a Flask app. It's a shared-memory object namespace for Apache Arrow-serializable objects, including pickle'd bytestrings generated by pickle.dumps(...).

The key difference with Apache Ray and Plasma is that it keeps track of object IDs for you. Any processes or threads or programs that are running on locally can share the variables' values by calling the name from any Brain object.

$ pip install brain-plasma
$ plasma_store -m 10000000 -s /tmp/plasma

from brain_plasma import Brain
brain = Brain(path='/tmp/plasma/)

brain['a'] = [1]*10000

brain['a']
# >>> [1,1,1,1,...]

jQuery add required to input fields

Using .attr method

.attr(attribute,value); // syntax

.attr("required", true);
// required="required"

.attr("required", false);
// 

Using .prop

.prop(property,value) // syntax

.prop("required", true);
// required=""

.prop("required", false);
//

Read more from here

https://stackoverflow.com/a/5876747/5413283

ValidateAntiForgeryToken purpose, explanation and example

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

Change color of Button when Mouse is over

<Button Background="#FF4148" BorderThickness="0" BorderBrush="Transparent">
     <Border HorizontalAlignment="Right" BorderBrush="#FF6A6A" BorderThickness="0>
     <Border.Style>
         <Style TargetType="Border">
             <Style.Triggers>
                 <Trigger Property="IsMouseOver" Value="True">
                     <Setter Property="Background" Value="#FF6A6A" />
                 </Trigger>
             </Style.Triggers>
         </Style>
      </Border.Style>
      <StackPanel Orientation="Horizontal">
           <Image  RenderOptions.BitmapScalingMode="HighQuality"   Source="//ImageName.png"   />
      </StackPanel>
      </Border>
  </Button>

How to access the elements of a function's return array?

<?php
function demo($val,$val1){
    return $arr=array("value"=>$val,"value1"=>$val1);

}
$arr_rec=demo(25,30);
echo $arr_rec["value"];
echo $arr_rec["value1"];
?>

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

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

Create a route without parameters:

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

Specify action with two parameters and attach the filter:

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

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

}

Filter that translates GET into action's arguments :

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

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

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

Reading a key from the Web.Config using ConfigurationManager

Sorry I've not tested this but I think it's done like this:

var filemap = new System.Configuration.ExeConfigurationFileMap();            
System.Configuration.Configuration config =  System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(filemap, System.Configuration.ConfigurationUserLevel.None);

//usage: config.AppSettings["xxx"]

Executing JavaScript after X seconds

setTimeout will help you to execute any JavaScript code based on the time you set.

Syntax

setTimeout(code, millisec, lang)

Usage,

setTimeout("function1()", 1000);

For more details, see http://www.w3schools.com/jsref/met_win_settimeout.asp

Can you issue pull requests from the command line on GitHub?

A man search like...

man git | grep pull | grep request

gives

git request-pull <start> <url> [<end>]

But, despite the name, it's not what you want. According to the docs:

Generate a request asking your upstream project to pull changes into their tree. The request, printed to the standard output, begins with the branch description, summarizes the changes and indicates from where they can be pulled.

@HolgerJust mentioned the github gem that does what you want:

sudo gem install gh 
gh pull-request [user] [branch]

Others have mentioned the official hub package by github:

sudo apt-get install hub

or

brew install hub 

then

hub pull-request [-focp] [-b <BASE>] [-h <HEAD>]

Expand and collapse with angular js

I just wrote a simple zippy/collapsable using Angular using ng-show, ng-click and ng-init. Its implemented to one level but can be expanded to multiple levels easily.

Assign a boolean variable to ng-show and toggle it on click of header.

Check it out here enter image description here

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

Try getParent() at the argument place of context like new AlertDialog.Builder(getParent()); Hope it will work, it worked for me.

How to pick just one item from a generator?

Generator is a function that produces an iterator. Therefore, once you have iterator instance, use next() to fetch the next item from the iterator. As an example, use next() function to fetch the first item, and later use for in to process remaining items:

# create new instance of iterator by calling a generator function
items = generator_function()

# fetch and print first item
first = next(items)
print('first item:', first)

# process remaining items:
for item in items:
    print('next item:', item)

SQL Switch/Case in 'where' clause

The problem with this is that when the SQL engine goes to evaluate the expression, it checks the FROM portion to pull the proper tables, and then the WHERE portion to provide some base criteria, so it cannot properly evaluate a dynamic condition on which column to check against.

You can use a WHERE clause when you're checking the WHERE criteria in the predicate, such as

WHERE account_location = CASE @locationType
                              WHEN 'business' THEN 45
                              WHEN 'area' THEN 52
                         END

so in your particular case, you're going to need put the query into a stored procedure or create three separate queries.

How to return a custom object from a Spring Data JPA GROUP BY query

I used custom DTO (interface) to map a native query to - the most flexible approach and refactoring-safe.

The problem I had with this - that surprisingly, the order of fields in the interface and the columns in the query matters. I got it working by ordering interface getters alphabetically and then ordering the columns in the query the same way.

How to call stopservice() method of Service class from the calling activity class

I actually used pretty much the same code as you above. My service registration in the manifest is the following

<service android:name=".service.MyService" android:enabled="true">
            <intent-filter android:label="@string/menuItemStartService" >
                <action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
            </intent-filter>
        </service>

In the service class I created an according constant string identifying the service name like:

public class MyService extends ForeGroundService {
    public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
   ...
}

and from the according Activity I call it with

startService(new Intent(MyService.MY_SERVICE));

and stop it with

stopService(new Intent(MyService.MY_SERVICE));

It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.

Multiple queries executed in java in single statement

I was wondering if it is possible to execute something like this using JDBC.

"SELECT FROM * TABLE;INSERT INTO TABLE;"

Yes it is possible. There are two ways, as far as I know. They are

  1. By setting database connection property to allow multiple queries, separated by a semi-colon by default.
  2. By calling a stored procedure that returns cursors implicit.

Following examples demonstrate the above two possibilities.

Example 1: ( To allow multiple queries ):

While sending a connection request, you need to append a connection property allowMultiQueries=true to the database url. This is additional connection property to those if already exists some, like autoReConnect=true, etc.. Acceptable values for allowMultiQueries property are true, false, yes, and no. Any other value is rejected at runtime with an SQLException.

String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";  

Unless such instruction is passed, an SQLException is thrown.

You have to use execute( String sql ) or its other variants to fetch results of the query execution.

boolean hasMoreResultSets = stmt.execute( multiQuerySqlString );

To iterate through and process results you require following steps:

READING_QUERY_RESULTS: // label  
    while ( hasMoreResultSets || stmt.getUpdateCount() != -1 ) {  
        if ( hasMoreResultSets ) {  
            Resultset rs = stmt.getResultSet();
            // handle your rs here
        } // if has rs
        else { // if ddl/dml/...
            int queryResult = stmt.getUpdateCount();  
            if ( queryResult == -1 ) { // no more queries processed  
                break READING_QUERY_RESULTS;  
            } // no more queries processed  
            // handle success, failure, generated keys, etc here
        } // if ddl/dml/...

        // check to continue in the loop  
        hasMoreResultSets = stmt.getMoreResults();  
    } // while results

Example 2: Steps to follow:

  1. Create a procedure with one or more select, and DML queries.
  2. Call it from java using CallableStatement.
  3. You can capture multiple ResultSets executed in procedure.
    DML results can't be captured but can issue another select
    to find how the rows are affected in the table.

Sample table and procedure:

mysql> create table tbl_mq( i int not null auto_increment, name varchar(10), primary key (i) );
Query OK, 0 rows affected (0.16 sec)

mysql> delimiter //
mysql> create procedure multi_query()
    -> begin
    ->  select count(*) as name_count from tbl_mq;
    ->  insert into tbl_mq( names ) values ( 'ravi' );
    ->  select last_insert_id();
    ->  select * from tbl_mq;
    -> end;
    -> //
Query OK, 0 rows affected (0.02 sec)
mysql> delimiter ;
mysql> call multi_query();
+------------+
| name_count |
+------------+
|          0 |
+------------+
1 row in set (0.00 sec)

+------------------+
| last_insert_id() |
+------------------+
|                3 |
+------------------+
1 row in set (0.00 sec)

+---+------+
| i | name |
+---+------+
| 1 | ravi |
+---+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Call Procedure from Java:

CallableStatement cstmt = con.prepareCall( "call multi_query()" );  
boolean hasMoreResultSets = cstmt.execute();  
READING_QUERY_RESULTS:  
    while ( hasMoreResultSets ) {  
        Resultset rs = stmt.getResultSet();
        // handle your rs here
    } // while has more rs

ToList().ForEach in Linq

You shouldn't use ForEach in that way. Read Lippert's “foreach” vs “ForEach”

If you want to be cruel with yourself (and the world), at least don't create useless List

employees.All(p => {
    collection.AddRange(p.Departments);
    p.Departments.All(u => { u.SomeProperty = null; return true; } );
    return true;
});

Note that the result of the All expression is a bool value that we are discarding (we are using it only because it "cycles" all the elements)

I'll repeat. You shouldn't use ForEach to change objects. LINQ should be used in a "functional" way (you can create new objects but you can't change old objects nor you can create side-effects). And what you are writing is creating so many useless List only to gain two lines of code...

How to pass parameter to function using in addEventListener?

If the this value you want is the just the object that you bound the event handler to, then addEventListener() already does that for you. When you do this:

productLineSelect.addEventListener('change', getSelection, false);

the getSelection function will already be called with this set to the object that the event handler was bound to. It will also be passed an argument that represents the event object which has all sorts of object information about the event.

function getSelection(event) {
    // this will be set to the object that the event handler was bound to
    // event is all the detailed information about the event
}

If the desired this value is some other value than the object you bound the event handler to, you can just do this:

var self = this;
productLineSelect.addEventListener('change',function() {
    getSelection(self)
},false);

By way of explanation:

  1. You save away the value of this into a local variable in your other event handler.
  2. You then create an anonymous function to pass addEventListener.
  3. In that anonymous function, you call your actual function and pass it the saved value of this.

Sorting a vector of custom objects

In C++20 one can default operator<=> without a user-defined comparator. The compiler will take care of that.

#include <iostream>
#include <compare>
#include <vector>
#include <algorithm>

struct MyInt
{
    int value;
    MyInt(int val) : value(val) {}
    auto operator<=>(const MyInt& other) const = default;
};


int main()
{
    MyInt Five(5);
    MyInt Two(2);
    MyInt Six(6);
    
    std::vector V{Five, Two, Six};
    std::sort(V.begin(), V.end());
    
    for (const auto& element : V)
        std::cout << element.value << std::endl;
}

Output:

2
5
6

How to remove old and unused Docker images

docker system prune -a

(You'll be asked to confirm the command. Use -f to force run, if you know what you're doing.)

Format numbers to strings in Python

You can use following to achieve desired functionality

"%d:%d:d" % (hours, minutes, seconds)

Order columns through Bootstrap4

2018 - Revisiting this question with the latest Bootstrap 4.

The responsive ordering classes are now order-first, order-last and order-0 - order-12

The Bootstrap 4 push pull classes are now push-{viewport}-{units} and pull-{viewport}-{units} and the xs- infix has been removed. To get the desired 1-3-2 layout on mobile/xs would be: Bootstrap 4 push pull demo (This only works pre 4.0 beta)


Bootstrap 4.1+

Since Bootstrap 4 is flexbox, it's easy to change the order of columns. The cols can be ordered from order-1 to order-12, responsively such as order-md-12 order-2 (last on md, 2nd on xs) relative to the parent .row.

<div class="container">
    <div class="row">
        <div class="col-3 col-md-6">
            <div class="card card-body">1</div>
        </div>
        <div class="col-6 col-md-12 order-2 order-md-12">
            <div class="card card-body">3</div>
        </div>
        <div class="col-3 col-md-6 order-3">
            <div class="card card-body">2</div>
        </div>
    </div>
</div>

Demo: Change order using order-* classes

Desktop (larger screens): enter image description here

Mobile (smaller screens): enter image description here

It's also possible to change column order using the flexbox direction utils...

<div class="container">
    <div class="row flex-column-reverse flex-md-row">
        <div class="col-md-8">
            2
        </div>
        <div class="col-md-4">
            1st on mobile
        </div>
    </div>
</div>

Demo: Bootstrap 4.1 Change Order with Flexbox Direction


Older version demos
demo - alpha 6
demo - beta (3)

See more Bootstrap 4.1+ ordering demos


Related:
Column ordering in Bootstrap 4 with push/pull and col-md-12
Bootstrap 4 change order of columns

A-C-B A-B-C

Best way to compare two complex objects

Thanks to the example of Jonathan. I expanded it for all cases (arrays, lists, dictionaries, primitive types).

This is a comparison without serialization and does not require the implementation of any interfaces for compared objects.

        /// <summary>Returns description of difference or empty value if equal</summary>
        public static string Compare(object obj1, object obj2, string path = "")
        {
            string path1 = string.IsNullOrEmpty(path) ? "" : path + ": ";
            if (obj1 == null && obj2 != null)
                return path1 + "null != not null";
            else if (obj2 == null && obj1 != null)
                return path1 + "not null != null";
            else if (obj1 == null && obj2 == null)
                return null;

            if (!obj1.GetType().Equals(obj2.GetType()))
                return "different types: " + obj1.GetType() + " and " + obj2.GetType();

            Type type = obj1.GetType();
            if (path == "")
                path = type.Name;

            if (type.IsPrimitive || typeof(string).Equals(type))
            {
                if (!obj1.Equals(obj2))
                    return path1 + "'" + obj1 + "' != '" + obj2 + "'";
                return null;
            }
            if (type.IsArray)
            {
                Array first = obj1 as Array;
                Array second = obj2 as Array;
                if (first.Length != second.Length)
                    return path1 + "array size differs (" + first.Length + " vs " + second.Length + ")";

                var en = first.GetEnumerator();
                int i = 0;
                while (en.MoveNext())
                {
                    string res = Compare(en.Current, second.GetValue(i), path);
                    if (res != null)
                        return res + " (Index " + i + ")";
                    i++;
                }
            }
            else if (typeof(System.Collections.IEnumerable).IsAssignableFrom(type))
            {
                System.Collections.IEnumerable first = obj1 as System.Collections.IEnumerable;
                System.Collections.IEnumerable second = obj2 as System.Collections.IEnumerable;

                var en = first.GetEnumerator();
                var en2 = second.GetEnumerator();
                int i = 0;
                while (en.MoveNext())
                {
                    if (!en2.MoveNext())
                        return path + ": enumerable size differs";

                    string res = Compare(en.Current, en2.Current, path);
                    if (res != null)
                        return res + " (Index " + i + ")";
                    i++;
                }
            }
            else
            {
                foreach (PropertyInfo pi in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public))
                {
                    try
                    {
                        var val = pi.GetValue(obj1);
                        var tval = pi.GetValue(obj2);
                        if (path.EndsWith("." + pi.Name))
                            return null;
                        var pathNew = (path.Length == 0 ? "" : path + ".") + pi.Name;
                        string res = Compare(val, tval, pathNew);
                        if (res != null)
                            return res;
                    }
                    catch (TargetParameterCountException)
                    {
                        //index property
                    }
                }
                foreach (FieldInfo fi in type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public))
                {
                    var val = fi.GetValue(obj1);
                    var tval = fi.GetValue(obj2);
                    if (path.EndsWith("." + fi.Name))
                        return null;
                    var pathNew = (path.Length == 0 ? "" : path + ".") + fi.Name;
                    string res = Compare(val, tval, pathNew);
                    if (res != null)
                        return res;
                }
            }
            return null;
        }

For easy copying of the code created repository

What is the "Temporary ASP.NET Files" folder for?

These are what's known as Shadow Copy Folders.

Simplistically....and I really mean it:

When ASP.NET runs your app for the first time, it copies any assemblies found in the /bin folder, copies any source code files (found for example in the App_Code folder) and parses your aspx, ascx files to c# source files. ASP.NET then builds/compiles all this code into a runnable application.

One advantage of doing this is that it prevents the possibility of .NET assembly DLL's #(in the /bin folder) becoming locked by the ASP.NET worker process and thus not updatable.

ASP.NET watches for file changes in your website and will if necessary begin the whole process all over again.

Theoretically the folder shouldn't need any maintenance, but from time to time, and only very rarely you may need to delete contents. That said, I work for a hosting company, we run up to 1200 sites per shared server and I haven't had to touch this folder on any of the 250 or so machines for years.

This is outlined in the MSDN article Understanding ASP.NET Dynamic Compilation

Draw a line in a div

Answered this just to emphasize @rblarsen comment on question :

You don't need the style tags in the CSS-file

If you remove the style tag from your css file it will work.

Apache2: 'AH01630: client denied by server configuration'

The problem is in VirtualHost but probablely is not

Require all granted

Confirm your config is correct,here is correct sample enter image description here

Set new id with jQuery

Did you try

$(this).val('test');

instead of

$(this).attr('value', 'test');

val() is generally easier, since the attribute you need to change may be different on different DOM elements.

Best way to get value from Collection by index

You can get the value from collection using for-each loop or using iterator interface. For a Collection c for (<ElementType> elem: c) System.out.println(elem); or Using Iterator Interface

 Iterator it = c.iterator(); 
        while (it.hasNext()) 
        System.out.println(it.next()); 

Properly Handling Errors in VBA (Excel)

This is what I'm teaching my students tomorrow. After years of looking at this stuff... ie all of the documentation above http://www.cpearson.com/excel/errorhandling.htm comes to mind as an excellent one...

I hope this summarizes it for others. There is an Err object and an active (or inactive) ErrorHandler. Both need to be handled and reset for new errors.

Paste this into a workbook and step through it with F8.

Sub ErrorHandlingDemonstration()

    On Error GoTo ErrorHandler

    'this will error
    Debug.Print (1 / 0)

    'this will also error
    dummy = Application.WorksheetFunction.VLookup("not gonna find me", Range("A1:B2"), 2, True)

    'silly error
    Dummy2 = "string" * 50

    Exit Sub

zeroDivisionErrorBlock:
    maybeWe = "did some cleanup on variables that shouldnt have been divided!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

vlookupFailedErrorBlock:
    maybeThisTime = "we made sure the value we were looking for was in the range!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

catchAllUnhandledErrors:
    MsgBox(thisErrorsDescription)
    Exit Sub

ErrorHandler:
    thisErrorsNumberBeforeReset = Err.Number
    thisErrorsDescription = Err.Description
    'this will reset the error object and error handling
    On Error GoTo 0
    'this will tell vba where to go for new errors, ie the new ErrorHandler that was previous just reset!
    On Error GoTo ErrorHandler

    ' 11 is the err.number for division by 0
    If thisErrorsNumberBeforeReset = 11 Then
        GoTo zeroDivisionErrorBlock
    ' 1004 is the err.number for vlookup failing
    ElseIf thisErrorsNumberBeforeReset = 1004 Then
        GoTo vlookupFailedErrorBlock
    Else
        GoTo catchAllUnhandledErrors
    End If

End Sub

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

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

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

C# Double - ToString() formatting with two decimal places but no rounding

Also note the CultureInformation of your system. Here my solution without rounding.

In this example you just have to define the variable MyValue as double. As result you get your formatted value in the string variable NewValue.

Note - Also set the C# using statement:

using System.Globalization;  

string MyFormat = "0";
if (MyValue.ToString (CultureInfo.InvariantCulture).Contains (CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator))
   {
      MyFormat += ".00";
   }

string NewValue = MyValue.ToString(MyFormat);

How can I get the named parameters from a URL using Flask?

Use request.args to get parsed contents of query string:

from flask import request

@app.route(...)
def login():
    username = request.args.get('username')
    password = request.args.get('password')

How to exit git log or git diff

In this case, as snarly suggested, typing q is the intended way to quit git log (as with most other pagers or applications that use pagers).

However normally, if you just want to abort a command that is currently executing, you can try ctrl+c (doesn't seem to work for git log, however) or ctrl+z (although in bash, ctrl-z will freeze the currently running foreground process, which can then be thawed as a background process with the bg command).

How change default SVN username and password to commit changes?

To use alternate credentials for a single operation, use the --username and --password switches for svn.

To clear previously-saved credentials, delete ~/.subversion/auth. You'll be prompted for credentials the next time they're needed.

These settings are saved in the user's home directory, so if you're using a shared account on "this laptop", be careful - if you allow the client to save your credentials, someone can impersonate you. The first option I provided is the better way to go in this case. At least until you stop using shared accounts on computers, which you shouldn't be doing.

To change credentials you need to do:

  • rm -rf ~/.subversion/auth
  • svn up ( it'll ask you for new username & password )

TypeError: expected a character buffer object - while trying to save integer to textfile

Just try the code below:

As I see you have inserted 'r+' or this command open the file in read mode so you are not able to write into it, so you have to open file in write mode 'w' if you want to overwrite the file contents and write new data, otherwise you can append data to file by using 'a'

I hope this will help ;)

f = open('testfile.txt', 'w')# just put 'w' if you want to write to the file 

x = f.readlines() #this command will read file lines

y = int(x)+1

print y
z = str(y) #making data as string to avoid buffer error
f.write(z)

f.close()

Linq code to select one item

Depends how much you like the linq query syntax, you can use the extension methods directly like:

var item = Items.First(i => i.Id == 123);

And if you don't want to throw an error if the list is empty, use FirstOrDefault which returns the default value for the element type (null for reference types):

var item = Items.FirstOrDefault(i => i.Id == 123);

if (item != null)
{
    // found it
}

Single() and SingleOrDefault() can also be used, but if you are reading from a database or something that already guarantees uniqueness I wouldn't bother as it has to scan the list to see if there's any duplicates and throws. First() and FirstOrDefault() stop on the first match, so they are more efficient.

Of the First() and Single() family, here's where they throw:

  • First() - throws if empty/not found, does not throw if duplicate
  • FirstOrDefault() - returns default if empty/not found, does not throw if duplicate
  • Single() - throws if empty/not found, throws if duplicate exists
  • SingleOrDefault() - returns default if empty/not found, throws if duplicate exists

select unique rows based on single distinct column

Quick one in TSQL

SELECT a.*
FROM emails a
INNER JOIN 
  (SELECT email,
    MIN(id) as id
  FROM emails 
  GROUP BY email 
) AS b
  ON a.email = b.email 
  AND a.id = b.id;

How do I "Add Existing Item" an entire directory structure in Visual Studio?

Enable "Show All Files" for the specific project (you might need to hit "Refresh" to see them)**.

The folders/files that are not part of your project appear slightly "lighter" in the project tree.

Right click the folders/files you want to add and click "Include In Project". It will recursively add folders/files to the project.

** These buttons are located on the mini Solution Explorer toolbar.

** Make sure you are NOT in debug mode.

How I can print to stderr in C?

#include<stdio.h>

int main ( ) {
    printf( "hello " );
    fprintf( stderr, "HELP!" );
    printf( " world\n" );
    return 0;
}

$ ./a.exe
HELP!hello  world
$ ./a.exe 2> tmp1
hello  world
$ ./a.exe 1> tmp1
HELP!$
  1. stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed. Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.

  2. Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.

Getting a "This application is modifying the autolayout engine from a background thread" error?

Main problem with "This application is modifying the autolayout engine from a background thread" is that it seem to be logged a long time after the actual problem occurs, this can make it very hard to troubleshoot.

I managed to solve the issue by creating three symbolic breakpoints.

Debug > Breakpoints > Create Symbolic Breakpoint...

Breakpoint 1:

  • Symbol: -[UIView setNeedsLayout]

  • Condition: !(BOOL)[NSThread isMainThread]

Breakpoint 2:

  • Symbol: -[UIView layoutIfNeeded]

  • Condition: !(BOOL)[NSThread isMainThread]

Breakpoint 3:

  • Symbol: -[UIView updateConstraintsIfNeeded]

  • Condition: !(BOOL)[NSThread isMainThread]

With these breakpoints, you can easily get a break on the actual line where you incorrectly call UI methods on non-main thread.

How can I see function arguments in IPython Notebook Server 3?

In 1.0, the functionality was bound to ( and tab and shift-tab, in 2.0 tab was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab. ( was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab.

So press Shift-Tab.

How to set a radio button in Android

btnDisplay.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

            // get selected radio button from radioGroup
        int selectedId = radioSexGroup.getCheckedRadioButtonId();

        // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);

        Toast.makeText(MyAndroidAppActivity.this,
            radioSexButton.getText(), Toast.LENGTH_SHORT).show();

    }

});

Replacing a character from a certain index

Strings in Python are immutable meaning you cannot replace parts of them.

You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.

You could for instance write a function:

def replace_str_index(text,index=0,replacement=''):
    return '%s%s%s'%(text[:index],replacement,text[index+1:])

And then for instance call it with:

new_string = replace_str_index(old_string,middle)

If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.

For instance:

replace_str_index('hello?bye',5)

will return 'hellobye'; and:

replace_str_index('hello?bye',5,'good')

will return 'hellogoodbye'.

How to generate UL Li list from string array using jquery?

var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i) {
    var li = $('<li/>')
        .addClass('ui-menu-item')
        .attr('role', 'menuitem')
        .appendTo(cList);
    var a = $('<a/>')
        .addClass('ui-all')
        .text( this )
        .appendTo(li);
});

Concatenating Files And Insert New Line In Between Files

In python, this concatenates with blank lines between files (the , suppresses adding an extra trailing blank line):

print '\n'.join(open(f).read() for f in filenames),

Here is the ugly python one-liner that can be called from the shell and prints the output to a file:

python -c "from sys import argv; print '\n'.join(open(f).read() for f in argv[1:])," File*.txt > finalfile.txt

ASP.NET Web API : Correct way to return a 401/unauthorised response

Just return the following:

return Unauthorized();

How to generate entire DDL of an Oracle schema (scriptable)?

The output of this query is very clean (original here)

clear screen
accept uname prompt 'Enter User Name : '
accept outfile prompt  ' Output filename : '

spool &&outfile..gen

SET LONG 20000 LONGCHUNKSIZE 20000 PAGESIZE 0 LINESIZE 1000 FEEDBACK OFF VERIFY OFF TRIMSPOOL ON

BEGIN
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
END;
/

SELECT dbms_metadata.get_ddl('USER','&&uname') FROM dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&&uname') from dual;

spool off

Ifelse statement in R with multiple conditions

How about?

DF$Den<-ifelse (is.na(DF$Denial1) | is.na(DF$Denial2) | is.na(DF$Denial3), "0", "1")

How do you return the column names of a table?

I use

SELECT st.NAME, sc.NAME, sc.system_type_id
FROM sys.tables st
INNER JOIN sys.columns sc ON st.object_id = sc.object_id
WHERE st.name LIKE '%Tablename%'

How to return multiple objects from a Java method?

In the event the method you're calling is private, or called from one location, try

return new Object[]{value1, value2};

The caller looks like:

Object[] temp=myMethod(parameters);
Type1 value1=(Type1)temp[0];  //For code clarity: temp[0] is not descriptive
Type2 value2=(Type2)temp[1];

The Pair example by David Hanak has no syntactic benefit, and is limited to two values.

return new Pair<Type1,Type2>(value1, value2);

And the caller looks like:

Pair<Type1, Type2> temp=myMethod(parameters);
Type1 value1=temp.a;  //For code clarity: temp.a is not descriptive
Type2 value2=temp.b;

What is the strict aliasing rule?

Type punning via pointer casts (as opposed to using a union) is a major example of breaking strict aliasing.

Refused to execute script, strict MIME type checking is enabled?

I solved my problem by adding just ${pageContext.request.contextPath} to my jsp path . in stead of :

 <script    src="static/js/jquery-3.2.1.min.js"></script>

I set :

 <script    src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script>

Variable's memory size in Python

Use sys.getsizeof to get the size of an object, in bytes.

>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>

Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.

How do I get a decimal value when using the division operator in Python?

There are three options:

>>> 4 / float(100)
0.04
>>> 4 / 100.0
0.04

which is the same behavior as the C, C++, Java etc, or

>>> from __future__ import division
>>> 4 / 100
0.04

You can also activate this behavior by passing the argument -Qnew to the Python interpreter:

$ python -Qnew
>>> 4 / 100
0.04

The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the // operator.

Edit: added section about -Qnew, thanks to ??O?????!

Why am I getting AttributeError: Object has no attribute

This may also occur if your using slots in class and have not added this new attribute in slots yet.

class xyz(object):
"""
class description

"""

__slots__ = ['abc', 'ijk']

def __init__(self):
   self.abc = 1
   self.ijk = 2
   self.pqr = 6 # This will throw error 'AttributeError: <name_of_class_object> object has no attribute 'pqr'

How can I determine the current CPU utilization from the shell?

Linux does not have any system variables that give the current CPU utilization. Instead, you have to read /proc/stat several times: each column in the cpu(n) lines gives the total CPU time, and you have to take subsequent readings of it to get percentages. See this document to find out what the various columns mean.

Select a Dictionary<T1, T2> with LINQ

The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.

class SomeObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

SomeObject[] objects = new SomeObject[]
{
    new SomeObject { ID = 1, Name = "Hello" },
    new SomeObject { ID = 2, Name = "World" }
};

Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);

Then objectDictionary[1] Would contain the value "Hello"

Git merge error "commit is not possible because you have unmerged files"

If you have fixed the conflicts you need to add the files to the stage with git add [filename], then commit as normal.

c# open file with default application and parameters

I converted the VB code in the blog post linked by xsl to C# and modified it a bit:

public static bool TryGetRegisteredApplication(
                     string extension, out string registeredApp)
{
    string extensionId = GetClassesRootKeyDefaultValue(extension);
    if (extensionId == null)
    {
        registeredApp = null;
        return false;
    }

    string openCommand = GetClassesRootKeyDefaultValue(
            Path.Combine(new[] {extensionId, "shell", "open", "command"}));

    if (openCommand == null)
    {
        registeredApp = null;
        return false;
    }

    registeredApp = openCommand
                     .Replace("%1", string.Empty)
                     .Replace("\"", string.Empty)
                     .Trim();
    return true;
}

private static string GetClassesRootKeyDefaultValue(string keyPath)
{
    using (var key = Registry.ClassesRoot.OpenSubKey(keyPath))
    {
        if (key == null)
        {
            return null;
        }

        var defaultValue = key.GetValue(null);
        if (defaultValue == null)
        {
            return null;
        }

        return defaultValue.ToString();
    }
}

EDIT - this is unreliable. See Finding the default application for opening a particular file type on Windows.

How to fix a header on scroll

Glorious, Pure-HTML/CSS Solution

In 2019 with CSS3 you can do this without Javascript at all. I frequently make sticky headers like this:

_x000D_
_x000D_
body {_x000D_
  overflow-y: auto;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
header {_x000D_
  position: sticky; /* Allocates space for the element, but moves it with you when you scroll */_x000D_
  top: 0; /* specifies the start position for the sticky behavior - 0 is pretty common */_x000D_
  width: 100%;_x000D_
  padding: 5px 0 5px 15px;_x000D_
  color: white;_x000D_
  background-color: #337AB7;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
div.big {_x000D_
  width: 100%;_x000D_
  min-height: 150vh;_x000D_
  background-color: #1ABB9C;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<body>_x000D_
<header><h1>Testquest</h1></header>_x000D_
<div class="big">Just something big enough to scroll on</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

how to have two headings on the same line in html

Check my sample solution

<h5 style="float: left; width: 50%;">Employee: Employee Name</h5>
<h5 style="float: right; width: 50%; text-align: right;">Employee: Employee Name</h5>

This will divide your page into two and insert the two header elements to the right and left part equally.

How to set standard encoding in Visual Studio

What

It is possible with EditorConfig.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.

This also includes file encoding.

EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.

How

You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset:

charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.

You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.

Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).

What next

While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.

integrating barcode scanner into php application?

I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.

How to start an Android application from the command line?

Example here.

Pasted below:

This is about how to launch android application from the adb shell.

Command: am

Look for invoking path in AndroidManifest.xml

Browser app::

# am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity
Starting: Intent { action=android.intent.action.MAIN comp={com.android.browser/com.android.browser.BrowserActivity} }
Warning: Activity not started, its current task has been brought to the front

Settings app::

# am start -a android.intent.action.MAIN -n com.android.settings/.Settings
Starting: Intent { action=android.intent.action.MAIN comp={com.android.settings/com.android.settings.Settings} }

Declaring array of objects

Using forEach we can store data in case we have already data we want to do some business login on data.

var sample = new Array();
var x = 10;
var sample = [1,2,3,4,5,6,7,8,9];
var data = [];

sample.forEach(function(item){
    data.push(item);
})

document.write(data);

Example by using simple for loop

var data = [];
for(var i = 0 ; i < 10 ; i++){
   data.push(i);
}
document.write(data);

Saving data to a file in C#

I just wrote a blog post on saving an object's data to Binary, XML, or Json. It sounds like you probably want to use Binary serialization, but perhaps you want the files to be edited outside of your app, in which case XML or Json might be better. Here are the functions to do it in the various formats. See my blog post for more details.

Binary

/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the XML file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the XML file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
    using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(stream, objectToWrite);
    }
}

/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the XML.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
    using (Stream stream = File.Open(filePath, FileMode.Open))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        return (T)binaryFormatter.Deserialize(stream);
    }
}

XML

Requires the System.Xml assembly to be included in your project.

/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        writer = new StreamWriter(filePath, append);
        serializer.Serialize(writer, objectToWrite);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        reader = new StreamReader(filePath);
        return (T)serializer.Deserialize(reader);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

Json

You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.

/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
        writer = new StreamWriter(filePath, append);
        writer.Write(contentsToWriteToFile);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        reader = new StreamReader(filePath);
        var fileContents = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<T>(fileContents);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

Example

// To save the characterSheet variable contents to a file.
WriteToBinaryFile<CharacterSheet>("C:\CharacterSheet.pfcsheet", characterSheet);

// To load the file contents back into a variable.
CharacterSheet characterSheet = ReadFromBinaryFile<CharacterSheet>("C:\CharacterSheet.pfcsheet");

How can I build for release/distribution on the Xcode 4?

The "play" button is specifically for build and run (or test or profile, etc). The Archive action is intended to build for release and to generate an archive that is suitable for submission to the app store. If you want to skip that, you can choose Product > Build For > Archive to force the release build without actually archiving. To find the built product, expand the Products group in the Project navigator, right-click the product and choose to show in Finder.

That said, you can click and hold the play button for a menu of other build actions (including Build and Archive).

deleting rows in numpy array

Here's a one liner (yes, it is similar to user333700's, but a little more straightforward):

>>> import numpy as np
>>> arr = np.array([[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222], 
                [ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]])
>>> print arr[arr.all(1)]
array([[ 0.96488889,  0.73641667,  0.67521429,  0.592875  ,  0.53172222]])

By the way, this method is much, much faster than the masked array method for large matrices. For a 2048 x 5 matrix, this method is about 1000x faster.

By the way, user333700's method (from his comment) was slightly faster in my tests, though it boggles my mind why.

How to get the full path of running process?

For others, if you want to find another process of the same executable, you can use:

public bool tryFindAnotherInstance(out Process process) {
    Process thisProcess = Process.GetCurrentProcess();
    string thisFilename = thisProcess.MainModule.FileName;
    int thisPId = thisProcess.Id;
    foreach (Process p in Process.GetProcesses())
    {
        try
        {
            if (p.MainModule.FileName == thisFilename && thisPId != p.Id)
            {
                process = p;
                return true;
            }
        }
        catch (Exception)
        {

        }
    }
    process = default;
    return false;
}

Use Ant for running program with command line arguments

What I did in the end is make a batch file to extract the CLASSPATH from the ant file, then run java directly using this:

In my build.xml:

<target name="printclasspath">
    <pathconvert property="classpathProp" refid="project.class.path"/>
    <echo>${classpathProp}</echo>
</target>

In another script called 'run.sh':

export CLASSPATH=$(ant -q printclasspath | grep echo | cut -d \  -f 7):build
java "$@"

It's no longer cross-platform, but at least it's relatively easy to use, and one could provide a .bat file that does the same as the run.sh. It's a very short batch script. It's not like migrating the entire build to platform-specific batch files.

I think it's a shame there's not some option in ant whereby you could do something like:

ant -- arg1 arg2 arg3

mpirun uses this type of syntax; ssh also can use this syntax I think.

Regular expression to match balanced parentheses

[^\(]*(\(.*\))[^\)]*

[^\(]* matches everything that isn't an opening bracket at the beginning of the string, (\(.*\)) captures the required substring enclosed in brackets, and [^\)]* matches everything that isn't a closing bracket at the end of the string. Note that this expression does not attempt to match brackets; a simple parser (see dehmann's answer) would be more suitable for that.

Can you have if-then-else logic in SQL?

You can make the following sql query

IF ((SELECT COUNT(*) FROM table1 WHERE project = 1) > 0) 
    SELECT product, price FROM table1 WHERE project = 1
ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 2) > 0) 
    SELECT product, price FROM table1 WHERE project = 2
ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 3) > 0)
    SELECT product, price FROM table1 WHERE project = 3

Class 'DOMDocument' not found

After a long time suffering from it in PHPunit...

For those using namespace, which is very common with Frameworks or CMS, a good check in addition to seeing if php-xml is installed and active, is to remember to declare the DOMDocument after the namespace:

namespace YourNameSpace\YourNameSpace;

use DOMDocument; //<--- here, check this!

Java count occurrence of each item in an array

I would use a hashtable with in key takes the element of the array (here string) and in value an Integer.

then go through the list doing something like this :

for(String s:array){
if(hash.containsKey(s)){
  Integer i = hash.get(s);
  i++;
}else{
  hash.put(s, new Interger(1));
}

how to access the command line for xampp on windows

Run PHP file from command Promp.

Please set Environment Variable as per below mention steps.

  1. Right Click on MY Computer Icon and Click on Properties or Go to "Control Panel\System and Security\System".
  2. Select "Advanced System Settings" and select "Advance" Tab
  3. Now Select "Environment Variable" option and select "Path" from "System Variables" and click on "Edit" button
  4. Now set path where php.exe file is available - For example if XAMPP install in to C: drive then Path is "C:\xampp\php"
  5. After set path Click Ok and Apply.

Now open Command prompt where your source file are available and run command "php test.php"

jQuery - replace all instances of a character in a string

You need to use a regular expression, so that you can specify the global (g) flag:

var s = 'some+multi+word+string'.replace(/\+/g, ' ');

(I removed the $() around the string, as replace is not a jQuery method, so that won't work at all.)

How to find the Target *.exe file of *.appref-ms

The appref-ms file does not point to the exe. When you hit that shortcut, it invokes the deployment manifest at the deployment provider url and checks for updates. It checks the application manifest (yourapp.exe.manifest) to see what files to download, and this file contains the definition of the entry point (i.e. the exe).

How do I use CMake?

Yes, cmake and make are different programs. cmake is (on Linux) a Makefile generator (and Makefile-s are the files driving the make utility). There are other Makefile generators (in particular configure and autoconf etc...). And you can find other build automation programs (e.g. ninja).

Restore a postgres backup file using the command line?

POSTGRESQL 9.1.12

DUMP:

pg_dump -U user db_name > archive_name.sql

put the user password and press enter.

RESTORE:

psql -U user db_name < /directory/archive.sql

put the user password and press enter.

What is the largest possible heap size with a 64-bit JVM?

In theory everything is possible but reality you find the numbers much lower than you might expect. I have been trying to address huge spaces on servers often and found that even though a server can have huge amounts of memory it surprised me that most software actually never can address it in real scenario's simply because the cpu's are not fast enough to really address them. Why would you say right ?! . Timings thats the endless downfall of every enormous machine which i have worked on. So i would advise to not go overboard by addressing huge amounts just because you can, but use what you think could be used. Actual values are often much lower than what you expected. Ofcourse non of us really uses hp 9000 systems at home and most of you actually ever will go near the capacity of your home system ever. For instance most users do not have more than 16 Gb of memory in their system. Ofcourse some of the casual gamers use work stations for a game once a month but i bet that is a very small percentage. So coming down to earth means i would address on a 8 Gb 64 bit system not much more than 512 mb for heapspace or if you go overboard try 1 Gb. I am pretty sure its even with these numbers pure overkill. I have constant monitored the memory usage during gaming to see if the addressing would make any difference but did not notice any difference at all when i addressed much lower values or larger ones. Even on the server/workstations there was no visible change in performance no matter how large i set the values. That does not say some jave users might be able to make use of more space addressed, but this far i have not seen any of the applications needing so much ever. Ofcourse i assume that their would be a small difference in performance if java instances would run out of enough heapspace to work with. This far i have not found any of it at all, however lack of real installed memory showed instant drops of performance if you set too much heapspace. When you have a 4 Gb system you run quickly out of heapspace and then you will see some errors and slowdowns because people address too much space which actually is not free in the system so the os starts to address drive space to make up for the shortage hence it starts to swap.

Random integer in VB.NET

Microsoft Example Rnd Function

https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx

1- Initialize the random-number generator.

Randomize()

2 - Generate random value between 1 and 6.

Dim value As Integer = CInt(Int((6 * Rnd()) + 1))

Usage of __slots__?

In Python, what is the purpose of __slots__ and what are the cases one should avoid this?

TLDR:

The special attribute __slots__ allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:

  1. faster attribute access.
  2. space savings in memory.

The space savings is from

  1. Storing value references in slots instead of __dict__.
  2. Denying __dict__ and __weakref__ creation if parent classes deny them and you declare __slots__.

Quick Caveats

Small caveat, you should only declare a particular slot one time in an inheritance tree. For example:

class Base:
    __slots__ = 'foo', 'bar'

class Right(Base):
    __slots__ = 'baz', 

class Wrong(Base):
    __slots__ = 'foo', 'bar', 'baz'        # redundant foo and bar

Python doesn't object when you get this wrong (it probably should), problems might not otherwise manifest, but your objects will take up more space than they otherwise should. Python 3.8:

>>> from sys import getsizeof
>>> getsizeof(Right()), getsizeof(Wrong())
(56, 72)

This is because the Base's slot descriptor has a slot separate from the Wrong's. This shouldn't usually come up, but it could:

>>> w = Wrong()
>>> w.foo = 'foo'
>>> Base.foo.__get__(w)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: foo
>>> Wrong.foo.__get__(w)
'foo'

The biggest caveat is for multiple inheritance - multiple "parent classes with nonempty slots" cannot be combined.

To accommodate this restriction, follow best practices: Factor out all but one or all parents' abstraction which their concrete class respectively and your new concrete class collectively will inherit from - giving the abstraction(s) empty slots (just like abstract base classes in the standard library).

See section on multiple inheritance below for an example.

Requirements:

  • To have attributes named in __slots__ to actually be stored in slots instead of a __dict__, a class must inherit from object.

  • To prevent the creation of a __dict__, you must inherit from object and all classes in the inheritance must declare __slots__ and none of them can have a '__dict__' entry.

There are a lot of details if you wish to keep reading.

Why use __slots__: Faster attribute access.

The creator of Python, Guido van Rossum, states that he actually created __slots__ for faster attribute access.

It is trivial to demonstrate measurably significant faster access:

import timeit

class Foo(object): __slots__ = 'foo',

class Bar(object): pass

slotted = Foo()
not_slotted = Bar()

def get_set_delete_fn(obj):
    def get_set_delete():
        obj.foo = 'foo'
        obj.foo
        del obj.foo
    return get_set_delete

and

>>> min(timeit.repeat(get_set_delete_fn(slotted)))
0.2846834529991611
>>> min(timeit.repeat(get_set_delete_fn(not_slotted)))
0.3664822799983085

The slotted access is almost 30% faster in Python 3.5 on Ubuntu.

>>> 0.3664822799983085 / 0.2846834529991611
1.2873325658284342

In Python 2 on Windows I have measured it about 15% faster.

Why use __slots__: Memory Savings

Another purpose of __slots__ is to reduce the space in memory that each object instance takes up.

My own contribution to the documentation clearly states the reasons behind this:

The space saved over using __dict__ can be significant.

SQLAlchemy attributes a lot of memory savings to __slots__.

To verify this, using the Anaconda distribution of Python 2.7 on Ubuntu Linux, with guppy.hpy (aka heapy) and sys.getsizeof, the size of a class instance without __slots__ declared, and nothing else, is 64 bytes. That does not include the __dict__. Thank you Python for lazy evaluation again, the __dict__ is apparently not called into existence until it is referenced, but classes without data are usually useless. When called into existence, the __dict__ attribute is a minimum of 280 bytes additionally.

In contrast, a class instance with __slots__ declared to be () (no data) is only 16 bytes, and 56 total bytes with one item in slots, 64 with two.

For 64 bit Python, I illustrate the memory consumption in bytes in Python 2.7 and 3.6, for __slots__ and __dict__ (no slots defined) for each point where the dict grows in 3.6 (except for 0, 1, and 2 attributes):

       Python 2.7             Python 3.6
attrs  __slots__  __dict__*   __slots__  __dict__* | *(no slots defined)
none   16         56 + 272†   16         56 + 112† | †if __dict__ referenced
one    48         56 + 272    48         56 + 112
two    56         56 + 272    56         56 + 112
six    88         56 + 1040   88         56 + 152
11     128        56 + 1040   128        56 + 240
22     216        56 + 3344   216        56 + 408     
43     384        56 + 3344   384        56 + 752

So, in spite of smaller dicts in Python 3, we see how nicely __slots__ scale for instances to save us memory, and that is a major reason you would want to use __slots__.

Just for completeness of my notes, note that there is a one-time cost per slot in the class's namespace of 64 bytes in Python 2, and 72 bytes in Python 3, because slots use data descriptors like properties, called "members".

>>> Foo.foo
<member 'foo' of 'Foo' objects>
>>> type(Foo.foo)
<class 'member_descriptor'>
>>> getsizeof(Foo.foo)
72

Demonstration of __slots__:

To deny the creation of a __dict__, you must subclass object:

class Base(object): 
    __slots__ = ()

now:

>>> b = Base()
>>> b.a = 'a'
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    b.a = 'a'
AttributeError: 'Base' object has no attribute 'a'

Or subclass another class that defines __slots__

class Child(Base):
    __slots__ = ('a',)

and now:

c = Child()
c.a = 'a'

but:

>>> c.b = 'b'
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    c.b = 'b'
AttributeError: 'Child' object has no attribute 'b'

To allow __dict__ creation while subclassing slotted objects, just add '__dict__' to the __slots__ (note that slots are ordered, and you shouldn't repeat slots that are already in parent classes):

class SlottedWithDict(Child): 
    __slots__ = ('__dict__', 'b')

swd = SlottedWithDict()
swd.a = 'a'
swd.b = 'b'
swd.c = 'c'

and

>>> swd.__dict__
{'c': 'c'}

Or you don't even need to declare __slots__ in your subclass, and you will still use slots from the parents, but not restrict the creation of a __dict__:

class NoSlots(Child): pass
ns = NoSlots()
ns.a = 'a'
ns.b = 'b'

And:

>>> ns.__dict__
{'b': 'b'}

However, __slots__ may cause problems for multiple inheritance:

class BaseA(object): 
    __slots__ = ('a',)

class BaseB(object): 
    __slots__ = ('b',)

Because creating a child class from parents with both non-empty slots fails:

>>> class Child(BaseA, BaseB): __slots__ = ()
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    class Child(BaseA, BaseB): __slots__ = ()
TypeError: Error when calling the metaclass bases
    multiple bases have instance lay-out conflict

If you run into this problem, You could just remove __slots__ from the parents, or if you have control of the parents, give them empty slots, or refactor to abstractions:

from abc import ABC

class AbstractA(ABC):
    __slots__ = ()

class BaseA(AbstractA): 
    __slots__ = ('a',)

class AbstractB(ABC):
    __slots__ = ()

class BaseB(AbstractB): 
    __slots__ = ('b',)

class Child(AbstractA, AbstractB): 
    __slots__ = ('a', 'b')

c = Child() # no problem!

Add '__dict__' to __slots__ to get dynamic assignment:

class Foo(object):
    __slots__ = 'bar', 'baz', '__dict__'

and now:

>>> foo = Foo()
>>> foo.boink = 'boink'

So with '__dict__' in slots we lose some of the size benefits with the upside of having dynamic assignment and still having slots for the names we do expect.

When you inherit from an object that isn't slotted, you get the same sort of semantics when you use __slots__ - names that are in __slots__ point to slotted values, while any other values are put in the instance's __dict__.

Avoiding __slots__ because you want to be able to add attributes on the fly is actually not a good reason - just add "__dict__" to your __slots__ if this is required.

You can similarly add __weakref__ to __slots__ explicitly if you need that feature.

Set to empty tuple when subclassing a namedtuple:

The namedtuple builtin make immutable instances that are very lightweight (essentially, the size of tuples) but to get the benefits, you need to do it yourself if you subclass them:

from collections import namedtuple
class MyNT(namedtuple('MyNT', 'bar baz')):
    """MyNT is an immutable and lightweight object"""
    __slots__ = ()

usage:

>>> nt = MyNT('bar', 'baz')
>>> nt.bar
'bar'
>>> nt.baz
'baz'

And trying to assign an unexpected attribute raises an AttributeError because we have prevented the creation of __dict__:

>>> nt.quux = 'quux'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyNT' object has no attribute 'quux'

You can allow __dict__ creation by leaving off __slots__ = (), but you can't use non-empty __slots__ with subtypes of tuple.

Biggest Caveat: Multiple inheritance

Even when non-empty slots are the same for multiple parents, they cannot be used together:

class Foo(object): 
    __slots__ = 'foo', 'bar'
class Bar(object):
    __slots__ = 'foo', 'bar' # alas, would work if empty, i.e. ()

>>> class Baz(Foo, Bar): pass
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    multiple bases have instance lay-out conflict

Using an empty __slots__ in the parent seems to provide the most flexibility, allowing the child to choose to prevent or allow (by adding '__dict__' to get dynamic assignment, see section above) the creation of a __dict__:

class Foo(object): __slots__ = ()
class Bar(object): __slots__ = ()
class Baz(Foo, Bar): __slots__ = ('foo', 'bar')
b = Baz()
b.foo, b.bar = 'foo', 'bar'

You don't have to have slots - so if you add them, and remove them later, it shouldn't cause any problems.

Going out on a limb here: If you're composing mixins or using abstract base classes, which aren't intended to be instantiated, an empty __slots__ in those parents seems to be the best way to go in terms of flexibility for subclassers.

To demonstrate, first, let's create a class with code we'd like to use under multiple inheritance

class AbstractBase:
    __slots__ = ()
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __repr__(self):
        return f'{type(self).__name__}({repr(self.a)}, {repr(self.b)})'

We could use the above directly by inheriting and declaring the expected slots:

class Foo(AbstractBase):
    __slots__ = 'a', 'b'

But we don't care about that, that's trivial single inheritance, we need another class we might also inherit from, maybe with a noisy attribute:

class AbstractBaseC:
    __slots__ = ()
    @property
    def c(self):
        print('getting c!')
        return self._c
    @c.setter
    def c(self, arg):
        print('setting c!')
        self._c = arg

Now if both bases had nonempty slots, we couldn't do the below. (In fact, if we wanted, we could have given AbstractBase nonempty slots a and b, and left them out of the below declaration - leaving them in would be wrong):

class Concretion(AbstractBase, AbstractBaseC):
    __slots__ = 'a b _c'.split()

And now we have functionality from both via multiple inheritance, and can still deny __dict__ and __weakref__ instantiation:

>>> c = Concretion('a', 'b')
>>> c.c = c
setting c!
>>> c.c
getting c!
Concretion('a', 'b')
>>> c.d = 'd'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Concretion' object has no attribute 'd'

Other cases to avoid slots:

  • Avoid them when you want to perform __class__ assignment with another class that doesn't have them (and you can't add them) unless the slot layouts are identical. (I am very interested in learning who is doing this and why.)
  • Avoid them if you want to subclass variable length builtins like long, tuple, or str, and you want to add attributes to them.
  • Avoid them if you insist on providing default values via class attributes for instance variables.

You may be able to tease out further caveats from the rest of the __slots__ documentation (the 3.7 dev docs are the most current), which I have made significant recent contributions to.

Critiques of other answers

The current top answers cite outdated information and are quite hand-wavy and miss the mark in some important ways.

Do not "only use __slots__ when instantiating lots of objects"

I quote:

"You would want to use __slots__ if you are going to instantiate a lot (hundreds, thousands) of objects of the same class."

Abstract Base Classes, for example, from the collections module, are not instantiated, yet __slots__ are declared for them.

Why?

If a user wishes to deny __dict__ or __weakref__ creation, those things must not be available in the parent classes.

__slots__ contributes to reusability when creating interfaces or mixins.

It is true that many Python users aren't writing for reusability, but when you are, having the option to deny unnecessary space usage is valuable.

__slots__ doesn't break pickling

When pickling a slotted object, you may find it complains with a misleading TypeError:

>>> pickle.loads(pickle.dumps(f))
TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled

This is actually incorrect. This message comes from the oldest protocol, which is the default. You can select the latest protocol with the -1 argument. In Python 2.7 this would be 2 (which was introduced in 2.3), and in 3.6 it is 4.

>>> pickle.loads(pickle.dumps(f, -1))
<__main__.Foo object at 0x1129C770>

in Python 2.7:

>>> pickle.loads(pickle.dumps(f, 2))
<__main__.Foo object at 0x1129C770>

in Python 3.6

>>> pickle.loads(pickle.dumps(f, 4))
<__main__.Foo object at 0x1129C770>

So I would keep this in mind, as it is a solved problem.

Critique of the (until Oct 2, 2016) accepted answer

The first paragraph is half short explanation, half predictive. Here's the only part that actually answers the question

The proper use of __slots__ is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. This saves the overhead of one dict for every object that uses slots

The second half is wishful thinking, and off the mark:

While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.

Python actually does something similar to this, only creating the __dict__ when it is accessed, but creating lots of objects with no data is fairly ridiculous.

The second paragraph oversimplifies and misses actual reasons to avoid __slots__. The below is not a real reason to avoid slots (for actual reasons, see the rest of my answer above.):

They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies.

It then goes on to discuss other ways of accomplishing that perverse goal with Python, not discussing anything to do with __slots__.

The third paragraph is more wishful thinking. Together it is mostly off-the-mark content that the answerer didn't even author and contributes to ammunition for critics of the site.

Memory usage evidence

Create some normal objects and slotted objects:

>>> class Foo(object): pass
>>> class Bar(object): __slots__ = ()

Instantiate a million of them:

>>> foos = [Foo() for f in xrange(1000000)]
>>> bars = [Bar() for b in xrange(1000000)]

Inspect with guppy.hpy().heap():

>>> guppy.hpy().heap()
Partition of a set of 2028259 objects. Total size = 99763360 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0 1000000  49 64000000  64  64000000  64 __main__.Foo
     1     169   0 16281480  16  80281480  80 list
     2 1000000  49 16000000  16  96281480  97 __main__.Bar
     3   12284   1   987472   1  97268952  97 str
...

Access the regular objects and their __dict__ and inspect again:

>>> for f in foos:
...     f.__dict__
>>> guppy.hpy().heap()
Partition of a set of 3028258 objects. Total size = 379763480 bytes.
 Index  Count   %      Size    % Cumulative  % Kind (class / dict of class)
     0 1000000  33 280000000  74 280000000  74 dict of __main__.Foo
     1 1000000  33  64000000  17 344000000  91 __main__.Foo
     2     169   0  16281480   4 360281480  95 list
     3 1000000  33  16000000   4 376281480  99 __main__.Bar
     4   12284   0    987472   0 377268952  99 str
...

This is consistent with the history of Python, from Unifying types and classes in Python 2.2

If you subclass a built-in type, extra space is automatically added to the instances to accomodate __dict__ and __weakrefs__. (The __dict__ is not initialized until you use it though, so you shouldn't worry about the space occupied by an empty dictionary for each instance you create.) If you don't need this extra space, you can add the phrase "__slots__ = []" to your class.

Windows batch - concatenate multiple text files into one

cat "input files" > "output files"

This works in PowerShell, which is the Windows preferred shell in current Windows versions, therefore it works. It is also the only version of the answers above to work with large files, where 'type' or 'copy' fails.

Comparing two java.util.Dates to see if they are in the same day

For Kotlin devs this is the version with comparing formatted strings approach:

val sdf = SimpleDateFormat("yyMMdd")
if (sdf.format(date1) == sdf.format(date2)) {
    // same day
}

It's not the best way, but it's short and working.

What is the purpose of flush() in Java streams?

From the docs of the flush method:

Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.

How can I limit possible inputs in a HTML5 "number" element?

You can specify it as text, but add pettern, that match numbers only:

<input type="text" pattern="\d*" maxlength="2">

It works perfect and also on mobile ( tested on iOS 8 and Android ) pops out the number keyboard.

JavaScript variable assignments from tuples

Here is a simple Javascript Tuple implementation:

var Tuple = (function () {
   function Tuple(Item1, Item2) {
      var item1 = Item1;
      var item2 = Item2;
      Object.defineProperty(this, "Item1", {
          get: function() { return item1  }
      });
      Object.defineProperty(this, "Item2", {
          get: function() { return item2  }
      });
   }
   return Tuple;
})();

var tuple = new Tuple("Bob", 25); // Instantiation of a new Tuple
var name = tuple.Item1; // Assignment. name will be "Bob"
tuple.Item1 = "Kirk"; // Will not set it. It's immutable.

This is a 2-tuple, however, you could modify my example to support 3,4,5,6 etc. tuples.

OVER clause in Oracle

You can use it to transform some aggregate functions into analytic:

SELECT  MAX(date)
FROM    mytable

will return 1 row with a single maximum,

SELECT  MAX(date) OVER (ORDER BY id)
FROM    mytable

will return all rows with a running maximum.

.gitignore all the .DS_Store files in every folder and subfolder

I think the problem you're having is that in some earlier commit, you've accidentally added .DS_Store files to the repository. Of course, once a file is tracked in your repository, it will continue to be tracked even if it matches an entry in an applicable .gitignore file.

You have to manually remove the .DS_Store files that were added to your repository. You can use

git rm --cached .DS_Store

Once removed, git should ignore it. You should only need the following line in your root .gitignore file: .DS_Store. Don't forget the period!

git rm --cached .DS_Store

removes only .DS_Store from the current directory. You can use

find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch

to remove all .DS_Stores from the repository.

Felt tip: Since you probably never want to include .DS_Store files, make a global rule. First, make a global .gitignore file somewhere, e.g.

echo .DS_Store >> ~/.gitignore_global

Now tell git to use it for all repositories:

git config --global core.excludesfile ~/.gitignore_global

This page helped me answer your question.

How to get the previous page URL using JavaScript?

You want in page A to know the URL of page B?

Or to know in page B the URL of page A?

In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?

In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains

Converting String to Double in Android

  kw=(EditText)findViewById(R.id.kw);
    btn=(Button)findViewById(R.id.btn);
    cost=(TextView )findViewById(R.id.cost);


            btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { cst =  Double.valueOf(kw.getText().toString());
            cst = cst*0.551;
            cost.setText(cst.toString());
        }
    });

convert strtotime to date time format in php

Use date() function to get the desired date

<?php
// set default timezone
date_default_timezone_set('UTC');

//define date and time
$strtotime = 1307595105;

// output
echo date('d M Y H:i:s',$strtotime);

// more formats
echo date('c',$strtotime); // ISO 8601 format
echo date('r',$strtotime); // RFC 2822 format
?>

Recommended online tool for strtotime to date conversion:

http://freeonlinetools24.com/

Android: Center an image

You can also use this,

android:layout_centerHorizontal="true"

The image will be placed at the center of the screen

Java 8 NullPointerException in Collectors.toMap

If the value is a String, then this might work: map.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> Optional.ofNullable(e.getValue()).orElse("")))

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

What exactly should be set in PYTHONPATH?

You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYTHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH.

ALTER COLUMN in sqlite

There's no ALTER COLUMN in sqlite.

I believe your only option is to:

  • Rename the table to a temporary name
  • Create a new table without the NOT NULL constraint
  • Copy the content of the old table to the new one
  • Remove the old table

This other Stackoverflow answer explains the process in details

how to query for a list<String> in jdbctemplate

Use following code

List data = getJdbcTemplate().queryForList(query,String.class)

creating a table in ionic

This is the way i use it. It's very simple and work very well.. Ionic html:

  <ion-content>
 

  <ion-grid class="ion-text-center">

    <ion-row class="ion-margin">
      <ion-col>
        <ion-title>
          <ion-text color="default">
            Your title remove if don't want use
          </ion-text>
        </ion-title>
      </ion-col>
    </ion-row>

    <ion-row class="header-row">
      <ion-col>
        <ion-text>Data</ion-text>
      </ion-col>

      <ion-col>
        <ion-text>Cliente</ion-text>
      </ion-col>

      <ion-col>
        <ion-text>Pagamento</ion-text>
      </ion-col>
    </ion-row>


    <ion-row>
      <ion-col>
        <ion-text>
            19/10/2020
        </ion-text>
      </ion-col>

        <ion-col>
          <ion-text>
            Nome
          </ion-text>
        </ion-col>
  
        <ion-col>
          <ion-text>
            R$ 200
          </ion-text>
        </ion-col>
    </ion-row>

  </ion-grid>
</ion-content>

CSS:

.header-row {
  background: #7163AA;
  color: #fff;
  font-size: 18px;
}

ion-col {
  border: 1px solid #ECEEEF;
}

Result of the code

window.onload vs $(document).ready()

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

How to have stored properties in Swift, the same way I had on Objective-C?

In PURE SWIFT with WEAK reference handling

import Foundation
import UIKit

extension CustomView {
    
    // can make private
    static let storedProperties = WeakDictionary<UIView, Properties>()
    
    struct Properties {
        var url: String = ""
        var status = false
        var desc: String { "url: \(url), status: \(status)" }
    }
    
    var properties: Properties {
        get {
            return CustomView.storedProperties.get(forKey: self) ?? Properties()
        }
        set {
            CustomView.storedProperties.set(forKey: self, object: newValue)
        }
    }
}

var view: CustomView? = CustomView()
print("1 print", view?.properties.desc ?? "nil")
view?.properties.url = "abc"
view?.properties.status = true
print("2 print", view?.properties.desc ?? "nil")
view = nil

WeakDictionary.swift

import Foundation

private class WeakHolder<T: AnyObject>: Hashable {
    weak var object: T?
    let hash: Int

    init(object: T) {
        self.object = object
        hash = ObjectIdentifier(object).hashValue
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(hash)
    }

    static func ==(lhs: WeakHolder, rhs: WeakHolder) -> Bool {
        return lhs.hash == rhs.hash
    }
}

class WeakDictionary<T1: AnyObject, T2> {
    private var dictionary = [WeakHolder<T1>: T2]()

    func set(forKey: T1, object: T2?) {
        dictionary[WeakHolder(object: forKey)] = object
    }

    func get(forKey: T1) -> T2? {
        let obj = dictionary[WeakHolder(object: forKey)]
        return obj
    }

    func forEach(_ handler: ((key: T1, value: T2)) -> Void) {
        dictionary.forEach {
            if let object = $0.key.object, let value = dictionary[$0.key] {
                handler((object, value))
            }
        }
    }
    
    func clean() {
        var removeList = [WeakHolder<T1>]()
        dictionary.forEach {
            if $0.key.object == nil {
                removeList.append($0.key)
            }
        }
        removeList.forEach {
            dictionary[$0] = nil
        }
    }
}

Make a bucket public in Amazon S3

Amazon provides a policy generator tool:

https://awspolicygen.s3.amazonaws.com/policygen.html

After that, you can enter the policy requirements for the bucket on the AWS console:

https://console.aws.amazon.com/s3/home

How to get the position of a character in Python?

A solution with numpy for quick access to all indexes:

string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

RESTART YOUR IDE

I tried all of the different things but nothing seems to be working then I just restarted my IDE and it worked like charm.

Still, if it does not work then try restarting your system.

FYI, I am working on the following versions

opencv-contrib-python==4.4.0.46
opencv-python==4.1.2.30

How to get rows count of internal table in abap?

Beside the recommended

DESCRIBE TABLE <itab-Name> LINES <variable>

there is also the system variable SY-TFILL.

From documentation:

After the statements DESCRIBE TABLE, LOOP AT and READ TABLE, the number of rows of the accessed internal table.

Example script:

REPORT ytest.

DATA pf_exclude TYPE TABLE OF sy-ucomm WITH HEADER LINE.

START-OF-SELECTION.
  APPEND '1' TO pf_exclude.
  APPEND '2' TO pf_exclude.
  APPEND '3' TO pf_exclude.
  APPEND '4' TO pf_exclude.

  WRITE: / 'sy-tfill = ', sy-tfill.

  DESCRIBE TABLE pf_exclude.
  WRITE: / 'sy-tfill = ', sy-tfill, 'after describe table'.

  sy-tfill = 0. "Reset
  READ TABLE pf_exclude INDEX 1 TRANSPORTING NO FIELDS.
  WRITE: / 'sy-tfill = ', sy-tfill, 'after read table'.


  sy-tfill = 0. "Reset
  LOOP AT pf_exclude.
    WRITE: / 'sy-tfill = ', sy-tfill, 'in loop with', pf_exclude.
    sy-tfill = 0. "Reset
  ENDLOOP.

The result:

sy-tfill =           0
sy-tfill =           4  after describe tabl
sy-tfill =           4  after read table
sy-tfill =           4  in loop with 1
sy-tfill =           0  in loop with 2
sy-tfill =           0  in loop with 3
sy-tfill =           0  in loop with 4

Please get attention of the value 0 for the 2nd entry: SY-TFILL is not updated with each step, only after the first loop.

I recommend the usage SY-TFILL only, if you need it direct after the READ(1)... If there are other commands between the READ and the usage of SY-TFILL, there is always the danger of a change of the system variable.

(1) or describe table.

Optimal way to DELETE specified rows from Oracle

In advance of my questions being answered, this is how I'd go about it:

Minimize the number of statements and the work they do issued in relative terms.

All scenarios assume you have a table of IDs (PURGE_IDS) to delete from TABLE_1, TABLE_2, etc.

Consider Using CREATE TABLE AS SELECT for really large deletes

If there's no concurrent activity, and you're deleting 30+ % of the rows in one or more of the tables, don't delete; perform a create table as select with the rows you wish to keep, and swap the new table out for the old table. INSERT /*+ APPEND */ ... NOLOGGING is surprisingly cheap if you can afford it. Even if you do have some concurrent activity, you may be able to use Online Table Redefinition to rebuild the table in-place.

Don't run DELETE statements you know won't delete any rows

If an ID value exists in at most one of the six tables, then keep track of which IDs you've deleted - and don't try to delete those IDs from any of the other tables.

CREATE TABLE TABLE1_PURGE NOLOGGING
AS 
SELECT ID FROM PURGE_IDS INNER JOIN TABLE_1 ON PURGE_IDS.ID = TABLE_1.ID;

DELETE FROM TABLE1 WHERE ID IN (SELECT ID FROM TABLE1_PURGE);

DELETE FROM PURGE_IDS WHERE ID IN (SELECT ID FROM TABLE1_PURGE);

DROP TABLE TABLE1_PURGE;

and repeat.

Manage Concurrency if you have to

Another way is to use PL/SQL looping over the tables, issuing a rowcount-limited delete statement. This is most likely appropriate if there's significant insert/update/delete concurrent load against the tables you're running the deletes against.

declare
  l_sql varchar2(4000);
begin
  for i in (select table_name from all_tables 
             where table_name in ('TABLE_1', 'TABLE_2', ...)
             order by table_name);
  loop
    l_sql := 'delete from ' || i.table_name || 
             ' where id in (select id from purge_ids) ' || 
             '   and rownum <= 1000000';
    loop
      commit;
      execute immediate l_sql;
      exit when sql%rowcount <> 1000000;  -- if we delete less than 1,000,000
    end loop;                             -- no more rows need to be deleted!
  end loop;
  commit;
end;

iPhone App Icons - Exact Radius?

People arguing about the corner radius being slightly increased but actually that's not the case.

From this blog:

A ‘secret’ of Apple’s physical products is that they avoid tangency (where a radius meets a line at a single point) and craft their surfaces with what’s called curvature continuity.

enter image description here

You don't need to apply corner radius to icons for iOS. Just provide square icons. But if you still want to know how, the actual shape is called Squircle and below is the formula:

enter image description here

In bash, how to store a return value in a variable?

Simplest answer:

the return code from a function can be only a value in the range from 0 to 255 . To store this value in a variable you have to do like in this example:

#!/bin/bash

function returnfunction {
    # example value between 0-255 to be returned 
    return 23
}

# note that the value has to be stored immediately after the function call :
returnfunction
myreturnvalue=$?

echo "myreturnvalue is "$myreturnvalue

how to run the command mvn eclipse:eclipse

The m2e plugin uses it's own distribution of Maven, packaged with the plugin.

In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows

Once Maven is properly installed (i.e. be sure that MAVEN_HOME, JAVA_HOME and PATH variables are set correctly): you must run mvn eclipse:eclipse from the directory containing the pom.xml.

General error: 1364 Field 'user_id' doesn't have a default value

User Auth::user()->id instead.

Here is the correct way :

//PostController
Post::create(request([
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => Auth::user()->id
]));

If your user is authenticated, Then Auth::user()->id will do the trick.

Correct way of getting Client's IP Addresses from http.Request

According to Mozilla MDN: "The X-Forwarded-For (XFF) header is a de-facto standard header for identifying the originating IP address of a client."
They publish clear information in their X-Forwarded-For article.

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

R command for setting working directory to source file location in Rstudio

If you work on Linux you can try this:

setwd(system("pwd", intern = T) )

It works for me.

What is the difference between Serializable and Externalizable in Java?

Serialization provides default functionality to store and later recreate the object. It uses verbose format to define the whole graph of objects to be stored e.g. suppose you have a linkedList and you code like below, then the default serialization will discover all the objects which are linked and will serialize. In default serialization the object is constructed entirely from its stored bits, with no constructor calls.

  ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream("/Users/Desktop/files/temp.txt"));
        oos.writeObject(linkedListHead); //writing head of linked list
        oos.close();

But if you want restricted serialization or don't want some portion of your object to be serialized then use Externalizable. The Externalizable interface extends the Serializable interface and adds two methods, writeExternal() and readExternal(). These are automatically called while serialization or deserialization. While working with Externalizable we should remember that the default constructer should be public else the code will throw exception. Please follow the below code:

public class MyExternalizable implements Externalizable
{

private String userName;
private String passWord;
private Integer roll;

public MyExternalizable()
{

}

public MyExternalizable(String userName, String passWord, Integer roll)
{
    this.userName = userName;
    this.passWord = passWord;
    this.roll = roll;
}

@Override
public void writeExternal(ObjectOutput oo) throws IOException 
{
    oo.writeObject(userName);
    oo.writeObject(roll);
}

@Override
public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException 
{
    userName = (String)oi.readObject();
    roll = (Integer)oi.readObject();
}

public String toString()
{
    StringBuilder b = new StringBuilder();
    b.append("userName: ");
    b.append(userName);
    b.append("  passWord: ");
    b.append(passWord);
    b.append("  roll: ");
    b.append(roll);

    return b.toString();
}
public static void main(String[] args)
{
    try
    {
        MyExternalizable m  = new MyExternalizable("nikki", "student001", 20);
        System.out.println(m.toString());
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/Desktop/files/temp1.txt"));
        oos.writeObject(m);
        oos.close();

        System.out.println("***********************************************************************");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/Desktop/files/temp1.txt"));
        MyExternalizable mm = (MyExternalizable)ois.readObject();
        mm.toString();
        System.out.println(mm.toString());
    } 
    catch (ClassNotFoundException ex) 
    {
        Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
    }
    catch(IOException ex)
    {
        Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

Here if you comment the default constructer then the code will throw below exception:

 java.io.InvalidClassException: javaserialization.MyExternalizable;     
 javaserialization.MyExternalizable; no valid constructor.

We can observe that as password is sensitive information, so i am not serializing it in writeExternal(ObjectOutput oo) method and not setting the value of same in readExternal(ObjectInput oi). That's the flexibility that is provided by Externalizable.

The output of the above code is as per below:

userName: nikki  passWord: student001  roll: 20
***********************************************************************
userName: nikki  passWord: null  roll: 20

We can observe as we are not setting the value of passWord so it's null.

The same can also be achieved by declaring the password field as transient.

private transient String passWord;

Hope it helps. I apologize if i made any mistakes. Thanks.

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

When the workbook first opens, execute this code:

alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"

Then just have a macro in the workbook called "EventMacro" that will repeat it.

Public Sub EventMacro()
    '... Execute your actions here'
    alertTime = Now + TimeValue("00:02:00")
    Application.OnTime alertTime, "EventMacro"
End Sub

Find and replace - Add carriage return OR Newline

Just a minor word of warning... a lot of environments use, or need, "\r\n" and not just "\n". I ran into an issue with Visual Studio not matching my regex string at the end of the line because I left off the "\r" of "\r\n", so my string couldn't match with a missing invisible character.

So, if you are doing a find, or a replace, consider the "\r".

For a little more detail on "\r" and "\n", see: https://stackoverflow.com/a/3451192/4427457

Get Value of a Edit Text field

A more advanced way would be to use butterknife bindview. This eliminates redundant code.

In your gradle under dependencies; add this 2 lines.

compile('com.jakewharton:butterknife:8.5.1') {
        exclude module: 'support-compat'
    }
apt 'com.jakewharton:butterknife-compiler:8.5.1'

Then sync up. Example binding edittext in MainActivity

import butterknife.BindView;   
import butterknife.ButterKnife; 

public class MainActivity {

@BindView(R.id.name) EditTextView mName; 
...

   public void onCreate(Bundle savedInstanceState){
         ButterKnife.bind(this); 
         ...
   }

}

But this is an alternative once you feel more comfortable or starting to work with lots of data.

Html encode in PHP

I searched for hours, and I tried almost everything suggested.
This worked for almost every entity :

$input = "ažškunrukiš ? àéò ??? ©€ ?? ? ?? ? R?";


echo htmlentities($input, ENT_HTML5  , 'UTF-8');

result :

&amacr;&zcaron;&scaron;&kcedil;&umacr;&ncedil;r&umacr;&kcedil;&imacr;&scaron; &cir; &agrave;&eacute;&ograve; &forall;&part;&ReverseElement; &copy;&euro; &clubs;&diamondsuit; &twoheadrightarrow; &harr;&nrarr; &swarr; &Rfr;&rx;rx;

Saving a select count(*) value to an integer (SQL Server)

Declare @MyInt int
Set @MyInt = ( Select Count(*) From MyTable )

If @MyInt > 0
Begin
    Print 'There''s something in the table'
End

I'm not sure if this is your issue, but you have to esacpe the single quote in the print statement with a second single quote. While you can use SELECT to populate the variable, using SET as you have done here is just fine and clearer IMO. In addition, you can be guaranteed that Count(*) will never return a negative value so you need only check whether it is greater than zero.

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

I had this same problem installing SQL Server 2014. Turns out it was due to a Windows Phone toolkit that I had installed back in 2010. If you run into this, make sure you uninstall any Windows phone stuff that isn't current.

I figured it out by looking at the log, which can be found by clicking "Detailed Report," which opens an HTML file. The file path is conveniently displayed within the HTML page. Open the directory that the file is in and look for "Detail.txt." Then search for the word "fail."

In my case there was a line showing WP_[something] as "Installed." I searched for the WP_ item and came across some blog posts about trouble uninstalling Windows Phone toolkits.

When I attempted to uninstall the windows phone I ran into more trouble. The uninstaller wanted to install three packages instead of uninstalling the toolkit. Eventually found this blog post: http://blogs.msdn.com/b/astebner/archive/2010/07/12/10037442.aspx linking to this XNA cleanup tool: http://blogs.msdn.com/b/astebner/archive/2009/04/10/9544320.aspx.

I ran the cleanup tool and finally SQL Server installer passed the check and allowed me to install. Hope this helps someone.

How to run regasm.exe from command line other than Visual Studio command prompt?

By dragging and dropping the dll onto 'regasm' you can register it. You can open two 'Window Explorer' windows. One will contain the dll you wish to register. The 2nd window will be the location of the 'regasm' application. Scroll down in both windows so that you have a view of both the dll and 'regasm'. It helps to reduce the size of the two windows so they are side-by-side. Be sure to drag the dll over the 'regasm' that is labeled 'application'. There are several 'regasm' files but you only want the application.

How to attach a file using mail command on Linux?

On Linux I would suggest,

# FILE_TO_BE_ATTACHED=abc.gz

uuencode abc.gz abc.gz > abc.gz.enc # This is optional, but good to have
                                    # to prevent binary file corruption.
                                    # also it make sure to get original 
                                    # file on other system, w/o worry of endianness

# Sending Mail, multiple attachments, and multiple receivers.
echo "Body Part of Mail" | mailx -s "Subject Line" -a attachment1 -a abc.gz.enc "[email protected] [email protected]"

Upon receiving mail attachment, if you have used uuencode, you would need uudecode

uudecode abc.gz.enc

# This will generate file as original with name as same as the 2nd argument for uuencode.

How to copy a file to another path?

I tried to copy an xml file from one location to another. Here is my code:

public void SaveStockInfoToAnotherFile()
{
    string sourcePath = @"C:\inetpub\wwwroot";
    string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
    string sourceFileName = "startingStock.xml";
    string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
    string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
    string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);

    if (!System.IO.Directory.Exists(destinationPath))
       {
         System.IO.Directory.CreateDirectory(destinationPath);
       }
    System.IO.File.Copy(sourceFile, destinationFile, true);
}

Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

How to create a circle icon button in Flutter?

My contribution:

import 'package:flutter/material.dart';

///
/// Create a circle button with an icon.
///
/// The [icon] argument must not be null.
///
class CircleButton extends StatelessWidget {
  const CircleButton({
    Key key,
    @required this.icon,
    this.padding = const EdgeInsets.all(8.0),
    this.color,
    this.onPressed,
    this.splashColor,
  })  : assert(icon != null),
        super(key: key);

  /// The [Icon] contained ny the circle button.
  final Icon icon;

  /// Empty space to inscribe inside the circle button. The [icon] is
  /// placed inside this padding.
  final EdgeInsetsGeometry padding;

  /// The color to fill in the background of the circle button.
  ///
  /// The [color] is drawn under the [icon].
  final Color color;

  /// The callback that is called when the button is tapped or otherwise activated.
  ///
  /// If this callback is null, then the button will be disabled.
  final void Function() onPressed;

  /// The splash color of the button's [InkWell].
  ///
  /// The ink splash indicates that the button has been touched. It
  /// appears on top of the button's child and spreads in an expanding
  /// circle beginning where the touch occurred.
  ///
  /// The default splash color is the current theme's splash color,
  /// [ThemeData.splashColor].
  final Color splashColor;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);

    return ClipOval(
      child: Material(
        type: MaterialType.button,
        color: color ?? theme.buttonColor,
        child: InkWell(
          splashColor: splashColor ?? theme.splashColor,
          child: Padding(
            padding: padding,
            child: icon,
          ),
          onTap: onPressed,
        ),
      ),
    );
  }
}

Can someone explain mappedBy in JPA and Hibernate?

mappedby speaks for itself, it tells hibernate not to map this field. it's already mapped by this field [name="field"].
field is in the other entity (name of the variable in the class not the table in the database)..

If you don't do that, hibernate will map this two relation as it's not the same relation

so we need to tell hibernate to do the mapping in one side only and co-ordinate between them.

HTTP Error 404 when running Tomcat from Eclipse

It is because there is no default ROOT web application. When you create some web app and deploy it to Tomcat using Eclipse, then you will be able to access it with the URL in the form of

http://localhost:8080/YourWebAppName

where YourWebAppName is some name you give to your web app (the so called application context path).

Quote from Jetty Documentation Wiki (emphasis mine):

The context path is the prefix of a URL path that is used to select the web application to which an incoming request is routed. Typically a URL in a Java servlet server is of the format http://hostname.com/contextPath/servletPath/pathInfo, where each of the path elements may be zero or more / separated elements. If there is no context path, the context is referred to as the root context.


If you still want the default app which is accessed with the URL of the form

http://localhost:8080

or if you change the default 8080 port to 80, then just

http://localhost

i.e. without application context path read the following (quote from Tutorial: Installing Tomcat 7 and Using it with Eclipse, emphasis mine):

Copy the ROOT (default) Web app into Eclipse. Eclipse forgets to copy the default apps (ROOT, examples, docs, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.34\webapps and copy the ROOT folder. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like C:\your-eclipse-workspace-location\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or .../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Google Text-To-Speech API

Expanding on Chris' answer. I managed to reverse engineer the token generation process.

The token for the request is based on the text and a global TKK variable set in the page script. These are hashed in JavaScript thus resulting in the tk param.

Somewhere in the page script you will find something like this:

TKK='403413';

This is the amount of hours passed since epoch.

The text is pumped in the following function (somewhat deobfuscated):

_x000D_
_x000D_
var query = "Hello person";_x000D_
var cM = function(a) {_x000D_
    return function() {_x000D_
        return a_x000D_
    }_x000D_
};_x000D_
var of = "=";_x000D_
var dM = function(a, b) {_x000D_
    for (var c = 0; c < b.length - 2; c += 3) {_x000D_
        var d = b.charAt(c + 2),_x000D_
            d = d >= t ? d.charCodeAt(0) - 87 : Number(d),_x000D_
            d = b.charAt(c + 1) == Tb ? a >>> d : a << d;_x000D_
        a = b.charAt(c) == Tb ? a + d & 4294967295 : a ^ d_x000D_
    }_x000D_
    return a_x000D_
};_x000D_
_x000D_
var eM = null;_x000D_
var cb = 0;_x000D_
var k = "";_x000D_
var Vb = "+-a^+6";_x000D_
var Ub = "+-3^+b+-f";_x000D_
var t = "a";_x000D_
var Tb = "+";_x000D_
var dd = ".";_x000D_
var hoursBetween = Math.floor(Date.now() / 3600000);_x000D_
window.TKK = hoursBetween.toString();_x000D_
_x000D_
fM = function(a) {_x000D_
    var b;_x000D_
    if (null === eM) {_x000D_
        var c = cM(String.fromCharCode(84)); // char 84 is T_x000D_
        b = cM(String.fromCharCode(75)); // char 75 is K_x000D_
        c = [c(), c()];_x000D_
        c[1] = b();_x000D_
        // So basically we're getting window.TKK_x000D_
        eM = Number(window[c.join(b())]) || 0_x000D_
    }_x000D_
    b = eM;_x000D_
_x000D_
    // This piece of code is used to convert d into the utf-8 encoding of a_x000D_
    var d = cM(String.fromCharCode(116)),_x000D_
        c = cM(String.fromCharCode(107)),_x000D_
        d = [d(), d()];_x000D_
    d[1] = c();_x000D_
    for (var c = cb + d.join(k) +_x000D_
            of, d = [], e = 0, f = 0; f < a.length; f++) {_x000D_
        var g = a.charCodeAt(f);_x000D_
_x000D_
        128 > g ? d[e++] = g : (2048 > g ? d[e++] = g >> 6 | 192 : (55296 == (g & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (g = 65536 + ((g & 1023) << 10) + (a.charCodeAt(++f) & 1023), d[e++] = g >> 18 | 240, d[e++] = g >> 12 & 63 | 128) : d[e++] = g >> 12 | 224, d[e++] = g >> 6 & 63 | 128), d[e++] = g & 63 | 128)_x000D_
    }_x000D_
_x000D_
_x000D_
    a = b || 0;_x000D_
    for (e = 0; e < d.length; e++) a += d[e], a = dM(a, Vb);_x000D_
    a = dM(a, Ub);_x000D_
    0 > a && (a = (a & 2147483647) + 2147483648);_x000D_
    a %= 1E6;_x000D_
    return a.toString() + dd + (a ^ b)_x000D_
};_x000D_
_x000D_
var token = fM(query);_x000D_
var url = "https://translate.google.com/translate_tts?ie=UTF-8&q="  + encodeURI(query) + "&tl=en&total=1&idx=0&textlen=12&tk=" + token + "&client=t";_x000D_
document.write(url);
_x000D_
_x000D_
_x000D_

I managed to successfully port this to python in my fork of gTTS, so I know this works.

Edit: By now the token generation code used by gTTS has been moved into gTTS-token.

Edit 2: Google has changed the API (somewhere around 2016-05-10), this method requires some modification. I'm currently working on this. In the meantime changing the client to tw-ob seems to work.

Edit 3:

The changes are minor, yet annoying to say the least. The TKK now has two parts. Looking something like 406986.2817744745. As you can see the first part has remained the same. The second part is the sum of two seemingly random numbers. TKK=eval('((function(){var a\x3d2680116022;var b\x3d137628723;return 406986+\x27.\x27+(a+b)})())'); Here \x3d means = and \x27 is '. Both a and b change every UTC minute. At one of the final steps in the algorithm the token is XORed by the second part.

The new token generation code is:

_x000D_
_x000D_
var xr = function(a) {_x000D_
    return function() {_x000D_
        return a_x000D_
    }_x000D_
};_x000D_
var yr = function(a, b) {_x000D_
    for (var c = 0; c < b.length - 2; c += 3) {_x000D_
        var d = b.charAt(c + 2)_x000D_
          , d = "a" <= d ? d.charCodeAt(0) - 87 : Number(d)_x000D_
          , d = "+" == b.charAt(c + 1) ? a >>> d : a << d;_x000D_
        a = "+" == b.charAt(c) ? a + d & 4294967295 : a ^ d_x000D_
    }_x000D_
    return a_x000D_
};_x000D_
var zr = null;_x000D_
var Ar = function(a) {_x000D_
    var b;_x000D_
    if (null  !== zr)_x000D_
        b = zr;_x000D_
    else {_x000D_
        b = xr(String.fromCharCode(84));_x000D_
        var c = xr(String.fromCharCode(75));_x000D_
        b = [b(), b()];_x000D_
        b[1] = c();_x000D_
        b = (zr = window[b.join(c())] || "") || ""_x000D_
    }_x000D_
    var d = xr(String.fromCharCode(116))_x000D_
      , c = xr(String.fromCharCode(107))_x000D_
      , d = [d(), d()];_x000D_
    d[1] = c();_x000D_
    c = "&" + d.join("") + _x000D_
    "=";_x000D_
    d = b.split(".");_x000D_
    b = Number(d[0]) || 0;_x000D_
    for (var e = [], f = 0, g = 0; g < a.length; g++) {_x000D_
        var l = a.charCodeAt(g);_x000D_
        128 > l ? e[f++] = l : (2048 > l ? e[f++] = l >> 6 | 192 : (55296 == (l & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (l = 65536 + ((l & 1023) << 10) + (a.charCodeAt(++g) & 1023),_x000D_
        e[f++] = l >> 18 | 240,_x000D_
        e[f++] = l >> 12 & 63 | 128) : e[f++] = l >> 12 | 224,_x000D_
        e[f++] = l >> 6 & 63 | 128),_x000D_
        e[f++] = l & 63 | 128)_x000D_
    }_x000D_
    a = b;_x000D_
    for (f = 0; f < e.length; f++)_x000D_
        a += e[f],_x000D_
        a = yr(a, "+-a^+6");_x000D_
    a = yr(a, "+-3^+b+-f");_x000D_
    a ^= Number(d[1]) || 0;_x000D_
    0 > a && (a = (a & 2147483647) + 2147483648);_x000D_
    a %= 1E6;_x000D_
    return c + (a.toString() + "." + (a ^ b))_x000D_
}_x000D_
;_x000D_
Ar("test");
_x000D_
_x000D_
_x000D_

Of course I can't generate a valid url anymore, since I don't know how a and b are generated.

add Shadow on UIView using swift 3

Please try this, it's working for me.

extension UIView {


func dropShadow() {

    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOffset = CGSize(width: 2, height: 3)
    layer.masksToBounds = false

    layer.shadowOpacity = 0.3
    layer.shadowRadius = 3
    //layer.shadowPath = UIBezierPath(rect: bounds).cgPath
    layer.rasterizationScale = UIScreen.main.scale
    layer.shouldRasterize = true
}}

Wildcards in jQuery selectors

for classes you can use:

div[class^="jander"]

Google API for location, based on user IP address

It looks like Google actively frowns on using IP-to-location mapping:

https://developers.google.com/maps/articles/geolocation?hl=en

That article encourages using the W3C geolocation API. I was a little skeptical, but it looks like almost every major browser already supports the geolocation API:

http://caniuse.com/geolocation

What's the difference between a proxy server and a reverse proxy server?

Here's an example of a reverse proxy (as a load balancer).

A client surfs to website.com and the server it hits has a reverse proxy running on it. The reverse proxy happens to be Pound. Pound takes the request and sends it to one of the three application servers sitting behind it. In this example, Pound is a load balancer. That is, it is balancing the load between three application servers.

The application servers serve up the website content back to the client.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.

As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline and Connect-MsolService, you will need to install the following applications (64-bit only):

  1. Applicable Operating Systems: Windows 7 to 10
    Name: "Microsoft Online Services Sign-in Assistant for IT Professionals RTW"
    Version: 7.250.4556.0 (latest)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=41950
    Installer file name: msoidcli_64.msi
  2. Applicable Operating Systems: Windows 7 to 10
    Name: "Windows Azure Active Directory Module for Windows PowerShell"
    Version: Unknown but the latest installer file's SHA-256 hash is D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
    Installer URL: https://technet.microsoft.com/en-us/library/dn975125.aspx
    Installer file name: AdministrationConfig-en.msi
  3. Applicable Operating Systems: Windows 7 only
    Name: "Windows PowerShell 3.0"
    Version: 3.0 (later versions will probably work too)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=34595
    Installer file name: Windows6.1-KB2506143-x64.msu

 

enter image description here enter image description here enter image description here

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

Reorder HTML table rows using drag-and-drop

Building upon the fiddle from @tim, this version tightens the scope and formatting, and converts bind() -> on(). It's designed to bind on a dedicated td as the handle instead of the entire row. In my use case, I have input fields so the "drag anywhere on the row" approach felt confusing.

Tested working on desktop. Only partial success with mobile touch. Can't get it to run correctly on SO's runnable snippet for some reason...

_x000D_
_x000D_
let ns = {
  drag: (e) => {
    let el = $(e.target),
      d = $('body'),
      tr = el.closest('tr'),
      sy = e.pageY,
      drag = false,
      index = tr.index();

    tr.addClass('grabbed');

    function move(e) {
      if (!drag && Math.abs(e.pageY - sy) < 10)
        return;
      drag = true;
      tr.siblings().each(function() {
        let s = $(this),
          i = s.index(),
          y = s.offset().top;
        if (e.pageY >= y && e.pageY < y + s.outerHeight()) {
          i < tr.index() ? s.insertAfter(tr) : s.insertBefore(tr);
          return false;
        }
      });
    }

    function up(e) {
      if (drag && index !== tr.index())
        drag = false;

      d.off('mousemove', move).off('mouseup', up);
      //d.off('touchmove', move).off('touchend', up); //failed attempt at touch compatibility
      tr.removeClass('grabbed');
    }
    d.on('mousemove', move).on('mouseup', up);
    //d.on('touchmove', move).on('touchend', up);
  }
};

$(document).ready(() => {
  $('body').on('mousedown touchstart', '.drag', ns.drag);
});
_x000D_
.grab {
  cursor: grab;
  user-select: none
}

tr.grabbed {
  box-shadow: 4px 1px 5px 2px rgba(0, 0, 0, 0.5);
}

tr.grabbed:active {
  user-input: none;
}

tr.grabbed:active * {
  user-input: none;
  cursor: grabbing !important;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th></th>
      <th>Drag the rows below...</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class='grab'>&vellip;</td>
      <td><input type="text" value="Row 1" /></td>
    </tr>
    <tr>
      <td class='grab'>&vellip;</td>
      <td><input type="text" value="Row 2" /></td>
    </tr>
    <tr>
      <td class='grab'>&vellip;</td>
      <td><input type="text" value="Row 3" /></td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

List directory tree structure in python?

For those who are still looking for an answer. Here is a recursive approach to get the paths in a dictionary.

import os


def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        dir_content = []
        for dir in dirs:
            go_inside = os.path.join(startpath, dir)
            dir_content.append(list_files(go_inside))
        files_lst = []
        for f in files:
            files_lst.append(f)
        return {'name': root, 'files': files_lst, 'dirs': dir_content}

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

You probably want to add one day rather than 24 hours. Not all days have 24 hours due to (among other circumstances) daylight saving time:

strtotime('+1 day', $timestamp);

Storing Python dictionaries

Pickle save:

try:
    import cPickle as pickle
except ImportError:  # Python 3.x
    import pickle

with open('data.p', 'wb') as fp:
    pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)

See the pickle module documentation for additional information regarding the protocol argument.

Pickle load:

with open('data.p', 'rb') as fp:
    data = pickle.load(fp)

JSON save:

import json

with open('data.json', 'w') as fp:
    json.dump(data, fp)

Supply extra arguments, like sort_keys or indent, to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure with indent=N spaces.

json.dump(data, fp, sort_keys=True, indent=4)

JSON load:

with open('data.json', 'r') as fp:
    data = json.load(fp)

Where do you include the jQuery library from? Google JSAPI? CDN?

There are a few issues here. Firstly, the async load method you specified:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load('jquery', '1.3.1');
  google.setOnLoadCallback(function() {
    // do stuff
  });
</script>

has a couple of issues. Script tags pause the page load while they are retrieved (if necessary). Now if they're slow to load this is bad but jQuery is small. The real problem with the above method is that because the jquery.js load happens independently for many pages, they will finish loading and render before jquery has loaded so any jquery styling you do will be a visible change for the user.

The other way is:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>

Try some simple examples like, have a simple table and change the background of the cells to yellow with the setOnLoadCallback() method vs $(document).ready() with a static jquery.min.js load. The second method will have no noticeable flicker. The first will. Personally I think that's not a good user experience.

As an example run this:

<html>
<head>
  <title>Layout</title>
  <style type="text/css">
    .odd { background-color: yellow; }
  </style>
</head>
<body>
<table>
  <tr><th>One</th><th>Two</th></tr>
  <tr><td>Three</td><td>Four</td></tr>
  <tr><td>Five</td><td>Six</td></tr>
  <tr><td>Seven</td><td>Nine</td></tr>
  <tr><td>Nine</td><td>Ten</td></tr>
</table> 
<script src="http://www.google.com/jsapi"></script>
<script>
  google.load("jquery", "1.3.1");
  google.setOnLoadCallback(function() {
    $(function() {
      $("tr:odd").addClass("odd");
    });
  });
</script>
</body>
</html>

You (should) see the table appear and then the rows go yellow.

The second problem with the google.load() method is that it only hosts a limited range of files. This is a problem for jquery since it is extremely plug-in dependent. If you try and include a jquery plugin with a <script src="..."> tag and google.load() the plug-in will probably fail with messages of "jQuery is not defined" because it hasn't loaded yet. I don't really see a way around this.

The third problem (with either method) is that they are one external load. Assuming you have some plugins and your own Javascript code you're up to a minimum of two external requests to load your Javascript. You're probably better off getting jquery, all relevant plug-ins and your own code and putting it into one minified file.

From Should You Use Google's Ajax Libraries API for Hosting?:

As to load times, you're actually loading two scripts - the jsapi script and the mootools script (the compressed version from above). So that is two connections, rather than one. In my experience, I found that the load time was actually 2-3 times slower than loading from my own personal shared server, even though it was coming from Google, and my version of the compressed file was a couple of K larger than Google's. This, even after the file had loaded and (presumably) cached. So for me, since the bandwidth doesn't matter much, isn't going to matter.

Lastly you have the potential problem of a paranoid browser flagging the request as some sort of XSS attempt. It's not typically a problem with default settings but on corporate networks where the user may not have control over which browser they use let alone the security settings you may have a problem.

So in the end I can't really see me using the Google AJAX API for jQuery at least (the more "complete" APIs are a different story in some ways) much except to post examples here.

Why is Thread.Sleep so harmful

I would like to answer this question from a coding-politics perspective, which may or may not be helpful to anyone. But particularly when you're dealing with tools that are intended for 9-5 corporate programmers, people who write documentation tend to use words like "should not" and "never" to mean "don't do this unless you really know what you're doing and why".

A couple of my other favorites in the C# world are that they tell you to "never call lock(this)" or "never call GC.Collect()". These two are forcefully declared in many blogs and official documentation, and IMO are complete misinformation. On some level this misinformation serves its purpose, in that it keeps the beginners away from doing things they don't understand before fully researching the alternatives, but at the same time, it makes it difficult to find REAL information via search-engines that all seem to point to articles telling you not to do something while offering no answer to the question "why not?"

Politically, it boils down to what people consider "good design" or "bad design". Official documentation should not be dictating the design of my application. If there's truly a technical reason that you shouldn't call sleep(), then IMO the documentation should state that it is totally okay to call it under specific scenarios, but maybe offer some alternative solutions that are scenario independent or more appropriate for the other scenarios.

Clearly calling "sleep()" is useful in many situations when deadlines are clearly defined in real-world-time terms, however, there are more sophisticated systems for waiting on and signalling threads that should be considered and understood before you start throwing sleep() into your code, and throwing unnecessary sleep() statements in your code is generally considered a beginners' tactic.

Attempted to read or write protected memory

I usually get "Attempted to read or write protected memory" when calling the "Show" method on some WinForms. I checked and there doesn't appear anything special about those forms. I don't know why this works (maybe someone can tell me) but usually moving the code that gets executed in the "Load" event of the form to the "Shown" event fixes it for me and I never see it again.

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

I had this and am mystified as to what has caused it, even after reading the above responses. My solution was to do

git reset --hard origin/master

Then that just resets my (local) copy of master (which I assume is screwed up) to the correct point, as represented by (remote) origin/master.

WARNING: You will lose all changes not yet pushed to origin/master.

How do I find which transaction is causing a "Waiting for table metadata lock" state?

I had a similar issue with Datagrip and none of these solutions worked.

Once I restarted the Datagrip Client it was no longer an issue and I could drop tables again.

How to set Spinner default value to null?

Merge this:

private long previousItemId = 0;

@Override
public long getItemId(int position) {
    long nextItemId = random.nextInt(Integer.MAX_VALUE);
    while(previousItemId == nextItemId) {
        nextItemId = random.nextInt(Integer.MAX_VALUE);
    }
    previousItemId = nextItemId;
    return nextItemId;
}

With this answer:

public class SpinnerInteractionListener
        implements AdapterView.OnItemSelectedListener, View.OnTouchListener {

    private AdapterView.OnItemSelectedListener onItemSelectedListener;

    public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
        this.onItemSelectedListener = selectedListener;
    }

    boolean userSelect = false;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        userSelect = true;
        return false;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if(userSelect) {
            onItemSelectedListener.onItemSelected(parent, view, pos, id);
            userSelect = false;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        if(userSelect) {
            onItemSelectedListener.onNothingSelected(parent);
            userSelect = false;
        }
    }
}

How to see PL/SQL Stored Function body in Oracle

SELECT text 
FROM all_source
where name = 'FGETALGOGROUPKEY'
order by line

alternatively:

select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY')
from dual;

dynamically set iframe src

Try this:

top.document.getElementById('AppFrame').setAttribute("src",fullPath);

Should I use int or Int32

Though they are (mostly) identical (see below for the one [bug] difference), you definitely should care and you should use Int32.

  • The name for a 16-bit integer is Int16. For a 64 bit integer it's Int64, and for a 32-bit integer the intuitive choice is: int or Int32?

  • The question of the size of a variable of type Int16, Int32, or Int64 is self-referencing, but the question of the size of a variable of type int is a perfectly valid question and questions, no matter how trivial, are distracting, lead to confusion, waste time, hinder discussion, etc. (the fact this question exists proves the point).

  • Using Int32 promotes that the developer is conscious of their choice of type. How big is an int again? Oh yeah, 32. The likelihood that the size of the type will actually be considered is greater when the size is included in the name. Using Int32 also promotes knowledge of the other choices. When people aren't forced to at least recognize there are alternatives it become far too easy for int to become "THE integer type".

  • The class within the framework intended to interact with 32-bit integers is named Int32. Once again, which is: more intuitive, less confusing, lacks an (unnecessary) translation (not a translation in the system, but in the mind of the developer), etc. int lMax = Int32.MaxValue or Int32 lMax = Int32.MaxValue?

  • int isn't a keyword in all .NET languages.

  • Although there are arguments why it's not likely to ever change, int may not always be an Int32.

The drawbacks are two extra characters to type and [bug].

This won't compile

public enum MyEnum : Int32
{
    AEnum = 0
}

But this will:

public enum MyEnum : int
{
    AEnum = 0
}

Dynamic Web Module 3.0 -- 3.1

Open Eclipse project properties, in Project Facets unselect "Dynamic Web Module",... Click OK Maven -> Update project

iOS 8 UITableView separator inset 0 not working

I went through all these wonderful answers and realized most of them do not work with iOS 8, or do work but the separator changes size during animation causing unwanted flashing. This is what I ended up doing in my app delegate before creating the window:

[[UITableView appearance] setSeparatorInset:UIEdgeInsetsZero];
[[UITableViewCell appearance] setSeparatorInset:UIEdgeInsetsZero];

if ([UITableView instancesRespondToSelector:@selector(setLayoutMargins:)]) {
    [[UITableView appearance] setLayoutMargins:UIEdgeInsetsZero];
    [[UITableViewCell appearance] setLayoutMargins:UIEdgeInsetsZero];
    [[UITableViewCell appearance] setPreservesSuperviewLayoutMargins:NO];
}

And this is what I added to my UITableViewController:

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

I didn't need to add anything else. Thanks to everyone who provided the crucial bits.

How can I install an older version of a package via NuGet?

As of NuGet 2.8, there is a feature to downgrade a package.

NuGet 2.8 Release Notes

Example:

The following command entered into the Package Manager Console will downgrade the Couchbase client to version 1.3.1.0.

Update-Package CouchbaseNetClient -Version 1.3.1.0

Result:

Updating 'CouchbaseNetClient' from version '1.3.3' to '1.3.1.0' in project [project name].
Removing 'CouchbaseNetClient 1.3.3' from [project name].
Successfully removed 'CouchbaseNetClient 1.3.3' from [project name].

Something to note as per crimbo below:

This approach doesn't work for downgrading from one prerelease version to other prerelease version - it only works for downgrading to a release version

Replace "\\" with "\" in a string in C#

Regex.Unescape(string) method converts any escaped characters in the input string.

The Unescape method performs one of the following two transformations:

  1. It reverses the transformation performed by the Escape method by removing the escape character ("\") from each character escaped by the method. These include the \, *, +, ?, |, {, [, (,), ^, $, ., #, and white space characters. In addition, the Unescape method unescapes the closing bracket (]) and closing brace (}) characters.

  2. It replaces the hexadecimal values in verbatim string literals with the actual printable characters. For example, it replaces @"\x07" with "\a", or @"\x0A" with "\n". It converts to supported escape characters such as \a, \b, \e, \n, \r, \f, \t, \v, and alphanumeric characters.

string str = @"a\\b\\c";
var output = System.Text.RegularExpressions.Regex.Unescape(str);

Reference:

https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.unescape?view=netframework-4.8

How to bind multiple values to a single WPF TextBlock?

Use a ValueConverter

[ValueConversion(typeof(string), typeof(String))]
public class MyConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Format("{0}:{1}", (string) value, (string) parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {

        return DependencyProperty.UnsetValue;
    }
}

and in the markup

<src:MyConverter x:Key="MyConverter"/>

. . .

<TextBlock Text="{Binding Name, Converter={StaticResource MyConverter Parameter=ID}}" />

ORA-12560: TNS:protocol adaptor error

Add to the enviroment vars the following varibale and value to identify the place of the tnsnames.ora file:

TNS_ADMIN

C:\oracle\product\10.2.0\client_1\network\admin

How to create a printable Twitter-Bootstrap page

Be sure to have a stylesheet assigned for printing.
It could be a separate stylesheet:

<link rel="stylesheet" type="text/css" media="print" href="print.css">

or one you share for all devices:

<link rel="stylesheet" type="text/css" href="bootstrap.min.css"> # Note there's no media attribute

Then, you can write your styles for printers in the separate stylesheets or in the shared one using media queries:

@media print {
    /* Your styles here */
}

How to generate all permutations of a list?

ANOTHER APPROACH (without libs)

def permutation(input):
    if len(input) == 1:
        return input if isinstance(input, list) else [input]

    result = []
    for i in range(len(input)):
        first = input[i]
        rest = input[:i] + input[i + 1:]
        rest_permutation = permutation(rest)
        for p in rest_permutation:
            result.append(first + p)
    return result

Input can be a string or a list

print(permutation('abcd'))
print(permutation(['a', 'b', 'c', 'd']))

Java: random long number in 0 <= x < n range

//use system time as seed value to get a good random number

   Random random = new Random(System.currentTimeMillis());
              long x;
             do{
                x=random.nextLong();
             }while(x<0 && x > n); 

//Loop until get a number greater or equal to 0 and smaller than n

Populating a ComboBox using C#

Set the ValueMember/DisplayMember properties to the name of the properties of your Language objects.

class Language
{
    string text;
    string value;

    public string Text
    {
        get 
        {
            return text;
        }
    }

    public string Value
    {
        get
        {
            return value;
        }
    }

    public Language(string text, string value)
    {
        this.text = text;
        this.value = value;
    }
}

...

combo.DisplayMember= "Text";
combo.ValueMember = "Value";
combo.Items.Add(new Language("English", "en"));

How do you determine what SQL Tables have an identity column programmatically

By some reason sql server save some identity columns in different tables, the code that work for me, is the following:

select      TABLE_NAME tabla,COLUMN_NAME columna
from        INFORMATION_SCHEMA.COLUMNS
where       COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
union all
select      o.name tabla, c.name columna
from        sys.objects o 
inner join  sys.columns c on o.object_id = c.object_id
where       c.is_identity = 1

Select top 10 records for each category

I do it this way:

SELECT a.* FROM articles AS a
  LEFT JOIN articles AS a2 
    ON a.section = a2.section AND a.article_date <= a2.article_date
GROUP BY a.article_id
HAVING COUNT(*) <= 10;

update: This example of GROUP BY works in MySQL and SQLite only, because those databases are more permissive than standard SQL regarding GROUP BY. Most SQL implementations require that all columns in the select-list that aren't part of an aggregate expression are also in the GROUP BY.

difference between iframe, embed and object elements

<iframe>

The iframe element represents a nested browsing context. HTML 5 standard - "The <iframe> element"

Primarily used to include resources from other domains or subdomains but can be used to include content from the same domain as well. The <iframe>'s strength is that the embedded code is 'live' and can communicate with the parent document.

<embed>

Standardised in HTML 5, before that it was a non standard tag, which admittedly was implemented by all major browsers. Behaviour prior to HTML 5 can vary ...

The embed element provides an integration point for an external (typically non-HTML) application or interactive content. (HTML 5 standard - "The <embed> element")

Used to embed content for browser plugins. Exceptions to this is SVG and HTML that are handled differently according to the standard.

The details of what can and can not be done with the embedded content is up to the browser plugin in question. But for SVG you can access the embedded SVG document from the parent with something like:

svg = document.getElementById("parent_id").getSVGDocument();

From inside an embedded SVG or HTML document you can reach the parent with:

parent = window.parent.document;

For embedded HTML there is no way to get at the embedded document from the parent (that I have found).

<object>

The <object> element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a nested browsing context, or as an external resource to be processed by a plugin. (HTML 5 standard - "The <object> element")

Conclusion

Unless you are embedding SVG or something static you are probably best of using <iframe>. To include SVG use <embed> (if I remember correctly <object> won't let you script†). Honestly I don't know why you would use <object> unless for older browsers or flash (that I don't work with).

† As pointed out in the comments below; scripts in <object> will run but the parent and child contexts can't communicate directly. With <embed> you can get the context of the child from the parent and vice versa. This means they you can use scripts in the parent to manipulate the child etc. That part is not possible with <object> or <iframe> where you would have to set up some other mechanism instead, such as the JavaScript postMessage API.

Passing event and argument to v-on in Vue.js

If you want to access event object as well as data passed, you have to pass event and ticket.id both as parameters, like following:

HTML

<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">

Javascript

methods: {
  addToCart: function (event, id) {
    // use event here as well as id
    console.log('In addToCart')
    console.log(id)
  }
}

See working fiddle: https://jsfiddle.net/nee5nszL/

Edited: case with vue-router

In case you are using vue-router, you may have to use $event in your v-on:input method like following:

<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">

Here is working fiddle.

What characters are forbidden in Windows and Linux directory names?

As of 18/04/2017, no simple black or white list of characters and filenames is evident among the answers to this topic - and there are many replies.

The best suggestion I could come up with was to let the user name the file however he likes. Using an error handler when the application tries to save the file, catch any exceptions, assume the filename is to blame (obviously after making sure the save path was ok as well), and prompt the user for a new file name. For best results, place this checking procedure within a loop that continues until either the user gets it right or gives up. Worked best for me (at least in VBA).

Read only the first line of a file?

first_line = next(open(filename))

setting JAVA_HOME & CLASSPATH in CentOS 6

Search here for centos jre install all users:

The easiest way to set an environment variable in CentOS is to use export as in

$> export JAVA_HOME=/usr/java/jdk.1.5.0_12

$> export PATH=$PATH:$JAVA_HOME

However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots. In such cases, you need to set the variables within the system wide profile. In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile. For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case: Create a new file called java.sh

vim /etc/profile.d/java.sh

Within this file, initialize the necessary environment variables

export JRE_HOME=/usr/java/jdk1.5.0_12/jre
export PATH=$PATH:$JRE_HOME/bin

export JAVA_HOME=/usr/java/jdk1.5.0_12
export JAVA_PATH=$JAVA_HOME

export PATH=$PATH:$JAVA_HOME/bin

Now when you restart your machine, the environment variables within java.sh will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded).

PS: If you want to load the environment variables within java.sh without having to restart the machine, you can use the source command as in:

$> source java.sh

Generate insert script for selected records?

SELECT 'INSERT SomeOtherDB.dbo.table(column1,column2,etc.)
  SELECT ' + CONVERT(VARCHAR(12), Pk_Id) + ','
       + '''' + REPLACE(ProductName, '''', '''''') + ''','
       + CONVERT(VARCHAR(12), Fk_CompanyId) + ','
       + CONVERT(VARCHAR(12), Price) + ';'
FROM dbo.unspecified_table_name
WHERE Fk_CompanyId = 1;

How do I count the number of rows and columns in a file using bash?

For rows you can simply use wc -l file

-l stands for total line

for columns uou can simply use head -1 file | tr ";" "\n" | wc -l

Explanation
head -1 file
Grabbing the first line of your file, which should be the headers, and sending to it to the next cmd through the pipe
| tr ";" "\n"

tr stands for translate.
It will translate all ; characters into a newline character.
In this example ; is your delimiter.

Then it sends data to next command.

wc -l
Counts the total number of lines.

How do I install soap extension?

In ubuntu to install php_soap on PHP7 use below commands. Reference

sudo apt-get install php7.0-soap
sudo systemctl restart apache2.service

For older version of php use below command and restart apache.

apt-get install php-soap

When should I create a destructor?

Destructors provide an implicit way of freeing unmanaged resources encapsulated in your class, they get called when the GC gets around to it and they implicitly call the Finalize method of the base class. If you're using a lot of unmanaged resources it is better to provide an explicit way of freeing those resources via the IDisposable interface. See the C# programming guide: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx

gcc/g++: "No such file or directory"

this works for me, sudo apt-get install libx11-dev

How can I get a list of all open named pipes in Windows?

At CMD prompt:

>ver

Microsoft Windows [Version 10.0.18362.476]

>dir \\.\pipe\\

Excel: the Incredible Shrinking and Expanding Controls

Although there are clearly numerous reasons for this behavior, several answers point to issues with scaling and screen resolutions. One workaround is to use the following functions to resize and anchor the controls to a specific cell:

Sub ResizeCombo(ByRef cbo As Shape, ByVal rw As Long, ByVal cl As Long, ByVal wid As Long)        
    cbo.Height = Intake.Cells(rw, cl).Height - 1
    cbo.Top = Intake.Cells(rw, cl).Top + 1
    cbo.Left = Intake.Cells(rw, cl).Left + 1
    cbo.Width = wid    
End Sub

Sub ResizeCheckbox(ByRef cbo As Shape, ByVal rw As Long, ByVal cl As Long)
    cbo.Height = Intake.Cells(rw, cl).Height - 1
    cbo.Top = Intake.Cells(rw, cl).Top + 1
    cbo.Left = Intake.Cells(rw, cl).Left + 6
    cbo.Width = Intake.Cells(rw, cl).MergeArea.Width - 7        
End Sub

Sub ResizeCombos()
    ResizeCombo Intake.Shapes("School"), 11, 1, 144

    ResizeCheckbox Intake.Shapes("cbReading"), 70, 1

    ''ResizeCombo also works for option buttons
    ResizeCombo Intake.Shapes("obGenderMale"), 20, 8, 45
    ResizeCombo Intake.Shapes("obGenderFemale"), 20, 9,50

HOWEVER, recently this workaround stopped working. I've been banging against it for days until I discovered that the zoom level of the sheet had been adjusted to 105%! Resetting it to 100% resolved the problem. However what if the user needs a higher zoom level? I figured out that I can change the zoom after resizing and things stay where they were meant to. My calling function now looks like this:

Sub refresh()
    OldZoom = ActiveWindow.Zoom
    ActiveWindow.Zoom = 100
    Call ResizeCombos
    ActiveWindow.Zoom = OldZoom
End Sub

So far it is working!

Android - drawable with rounded corners at the top only

Create roung_top_corners.xml on drawable and copy the below code

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
    android:topLeftRadius="22dp"
    android:topRightRadius="22dp"
    android:bottomLeftRadius="0dp"
    android:bottomRightRadius="0dp"
    />
<gradient
    android:angle="180"
    android:startColor="#1d2b32"
    android:centerColor="#465059"
    android:endColor="#687079"
    android:type="linear" />
<padding
    android:left="0dp"
    android:top="0dp"
    android:right="0dp"
    android:bottom="0dp"
    />
<size
    android:width="270dp"
    android:height="60dp"
    /></shape>

what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

Given this example url:

http://www.example.com/some-dir/yourpage.php?q=bogus&n=10

$_SERVER['REQUEST_URI'] will give you:

/some-dir/yourpage.php?q=bogus&n=10

Whereas $_GET['q'] will give you:

bogus

In other words, $_SERVER['REQUEST_URI'] will hold the full request path including the querystring. And $_GET['q'] will give you the value of parameter q in the querystring.