Programs & Examples On #Window managers

A Window Manager is a service on most modern OSes which provides the UI for manipulating the location and sizes of windows.

Print Combining Strings and Numbers

In Python 3.6

a, b=1, 2 

print ("Value of variable a is: ", a, "and Value of variable b is :", b)

print(f"Value of a is: {a}")

The action or event has been blocked by Disabled Mode

No. Go to database tools (for 2007) and click checkmark on the Message Bar. Then, after the message bar apears, click on Options, and then Enable. Hope this helps.

Dimitri

How do I display images from Google Drive on a website?

i supposed you uploaded your photo in your drive all what you need to do is while you are opening your google drive just open your dev tools in chrome and head to your img tag and copy the link beside the src attribute and use it

How to unpublish an app in Google Play Developer Console

To unpublish your app on the Google Play store:

  1. Go to https://market.android.com/publish/Home, and log in to your Google Play account.
  2. Click on the application you want to delete.
  3. Click on the Store Presence menu, and click the “Pricing and Distribution” item.
  4. Click Unpublish

XAMPP installation on Win 8.1 with UAC Warning

You can solve the issue by

  1. Ignore the warning and Install XAMPP directly under C:/ folder. It will solve your issue
  2. You can deactivate the UAC which i don't recommend. It's makes your PC less secure.

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

Remove element by id

Functions that use ele.parentNode.removeChild(ele) won't work for elements you've created but not yet inserted into the HTML. Libraries like jQuery and Prototype wisely use a method like the following to evade that limitation.

_limbo = document.createElement('div');
function deleteElement(ele){
    _limbo.appendChild(ele);
    _limbo.removeChild(ele);
}

I think JavaScript works like that because the DOM's original designers held parent/child and previous/next navigation as a higher priority than the DHTML modifications that are so popular today. Being able to read from one <input type='text'> and write to another by relative location in the DOM was useful in the mid-90s, a time when the dynamic generation of entire HTML forms or interactive GUI elements was barely a twinkle in some developer's eye.

Strip out HTML and Special Characters

In a more detailed manner from Above example, Considering below is your string:

$string = '<div>This..</div> <a>is<a/> <strong>hello</strong> <i>world</i> ! ??? ?? ????? ??????! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text ?? ???? test 123 ?,.m,............ ~~~ ??]??}~?]?}"; ';

Code:

echo preg_replace('/[^A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));

Allows: English letters (Capital and small), 0 to 9 and characters !@#$%^&*().

Removes: All html tags, and special characters other than above

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

Git: How to remove file from index without deleting files from any repository

After doing the git rm --cached command, try adding myfile to the .gitignore file (create one if it does not exist). This should tell git to ignore myfile.

The .gitignore file is versioned, so you'll need to commit it and push it to the remote repository.

What is the default value for enum variable?

I think it's quite dangerous to rely on the order of the values in a enum and to assume that the first is always the default. This would be good practice if you are concerned about protecting the default value.

enum E
{
    Foo = 0, Bar, Baz, Quux
}

Otherwise, all it takes is a careless refactor of the order and you've got a completely different default.

Text not wrapping in p tag

add float: left property to the image.

#rb-menu-com li .submenu div img {
    border:1px solid #fff;
    float:left;
}

Read large files in Java

This is a very good article: http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/

In summary, for great performance, you should:

  1. Avoid accessing the disk.
  2. Avoid accessing the underlying operating system.
  3. Avoid method calls.
  4. Avoid processing bytes and characters individually.

For example, to reduce the access to disk, you can use a large buffer. The article describes various approaches.

How to Decrease Image Brightness in CSS

I found this today. It really helped me. http://www.propra.nl/playground/css_filters/

All you need is to add this to your css style.:

div {-webkit-filter: brightness(57%)}

How to detect the end of loading of UITableView

I always use this very simple solution:

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] == lastRow){
        //end of loading
        //for example [activityIndicator stopAnimating];
    }
}

How to get a Static property with Reflection

Just wanted to clarify this for myself, while using the new reflection API based on TypeInfo - where BindingFlags is not available reliably (depending on target framework).

In the 'new' reflection, to get the static properties for a type (not including base class(es)) you have to do something like:

IEnumerable<PropertyInfo> props = 
  type.GetTypeInfo().DeclaredProperties.Where(p => 
    (p.GetMethod != null && p.GetMethod.IsStatic) ||
    (p.SetMethod != null && p.SetMethod.IsStatic));

Caters for both read-only or write-only properties (despite write-only being a terrible idea).

The DeclaredProperties member, too doesn't distinguish between properties with public/private accessors - so to filter around visibility, you then need to do it based on the accessor you need to use. E.g - assuming the above call has returned, you could do:

var publicStaticReadable = props.Where(p => p.GetMethod != null && p.GetMethod.IsPublic);

There are some shortcut methods available - but ultimately we're all going to be writing a lot more extension methods around the TypeInfo query methods/properties in the future. Also, the new API forces us to think about exactly what we think of as a 'private' or 'public' property from now on - because we must filter ourselves based on individual accessors.

I have filtered my Excel data and now I want to number the rows. How do I do that?

Okay I found the correct answer to this issue here

Here are the steps:

  1. Filter your data.
  2. Select the cells you want to add the numbering to.
  3. Press F5.
  4. Select Special.
  5. Choose "Visible Cells Only" and press OK.
  6. Now in the top row of your filtered data (just below the header) enter the following code:

    =MAX($"Your Column Letter"$1:"Your Column Letter"$"The current row for the filter - 1") + 1

    Ex:

    =MAX($A$1:A26)+1

    Which would be applied starting at cell A27.

  7. Hold Ctrl and press enter.

Note this only works in a range, not in a table!

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

How can I break from a try/catch block without throwing an exception in Java

In this sample in catch block i change the value of counter and it will break while block:

class TestBreak {
    public static void main(String[] a) {
        int counter = 0;

        while(counter<5) {
            try {
                counter++;
                int x = counter/0;
            }
            catch(Exception e) {
                counter = 1000;    
            }
        }
    }
}k

Excel function to get first word from sentence in other cell

If you want to cater to 1-word cell, use this... based upon astander's

=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)

How can I select the first day of a month in SQL?

Here we can use below query to the first date of the month and last date of the month.

SELECT DATEADD(DAY,1,EOMONTH(Getdate(),-1)) as 'FD',Cast(Getdate()-1 as Date)
as 'LD'

Using the Jersey client to do a POST operation

It is now the first example in the Jersey Client documentation

Example 5.1. POST request with form parameters

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");

Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");

MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
    .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
        MyJAXBBean.class);

Downloading a large file using curl

when curl is used to download a large file then CURLOPT_TIMEOUT is the main option you have to set for.

CURLOPT_RETURNTRANSFER has to be true in case you are getting file like pdf/csv/image etc.

You may find the further detail over here(correct url) Curl Doc

From that page:

curl_setopt($request, CURLOPT_TIMEOUT, 300); //set timeout to 5 mins

curl_setopt($request, CURLOPT_RETURNTRANSFER, true); // true to get the output as string otherwise false

What are the correct version numbers for C#?

C# Version History:

C# is a simple and powerful object-oriented programming language developed by Microsoft.

C# has evolved much since its first release in 2002. C# was introduced with .NET Framework 1.0.

The following table lists important features introduced in each version of C#.

And the latest version of C# is available in C# Versions.

1: enter image description here

Elastic Search: how to see the indexed data

A tool that helps me a lot to debug ElasticSearch is ElasticHQ. Basically, it is an HTML file with some JavaScript. No need to install anywhere, let alone in ES itself: just download it, unzip int and open the HTML file with a browser.

Not sure it is the best tool for ES heavy users. Yet, it is really practical to whoever is in a hurry to see the entries.

How to choose the right bean scope?

Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.


From JSF 2.3 here are scopes that can be used on JSF Backing Beans:

1. @javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.

2. @javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.

3. @javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.

4. @javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

5. @javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.

6. @javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.


The following legacy answer applies JSF version before 2.3

As of JSF 2.x there are 4 Bean Scopes:

  • @SessionScoped
  • @RequestScoped
  • @ApplicationScoped
  • @ViewScoped

Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.

RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.

ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.

Choose the scope you based on your requirement.

Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54] enter image description here

Finding rows that don't contain numeric data in Oracle

To get an indicator:

DECODE( TRANSLATE(your_number,' 0123456789',' ')

e.g.

SQL> select DECODE( TRANSLATE('12345zzz_not_numberee',' 0123456789',' '), NULL, 'number','contains char')
 2 from dual
 3 /

"contains char"

and

SQL> select DECODE( TRANSLATE('12345',' 0123456789',' '), NULL, 'number','contains char')
 2 from dual
 3 /

"number"

and

SQL> select DECODE( TRANSLATE('123405',' 0123456789',' '), NULL, 'number','contains char')
 2 from dual
 3 /

"number"

Oracle 11g has regular expressions so you could use this to get the actual number:

SQL> SELECT colA
  2  FROM t1
  3  WHERE REGEXP_LIKE(colA, '[[:digit:]]');

COL1
----------
47845
48543
12
...

If there is a non-numeric value like '23g' it will just be ignored.

Javascript Audio Play on click

While several answers are similar, I still had an issue - the user would click the button several times, playing the audio over itself (either it was clicked by accident or they were just 'playing'....)

An easy fix:

var music = new Audio();
function playMusic(file) {
    music.pause();
    music = new Audio(file);
    music.play();
}

Setting up the audio on load allowed 'music' to be paused every time the function is called - effectively stopping the 'noise' even if they user clicks the button several times (and there is also no need to turn off the button, though for user experience it may be something you want to do).

Converting Symbols, Accent Letters to English Alphabet

Since the encoding that turns "the Family" into "t?? T???ly" is effectively random and not following any algorithm that can be explained by the information of the Unicode codepoints involved, there's no general way to solve this algorithmically.

You will need to build the mapping of Unicode characters into latin characters which they resemble. You could probably do this with some smart machine learning on the actual glyphs representing the Unicode codepoints. But I think the effort for this would be greater than manually building that mapping. Especially if you have a good amount of examples from which you can build your mapping.

To clarify: a few of the substitutions can actually be solved via the Unicode data (as the other answers demonstrate), but some letters simply have no reasonable association with the latin characters which they resemble.

Examples:

  • "?" (U+0452 CYRILLIC SMALL LETTER DJE) is more related to "d" than to "h", but is used to represent "h".
  • "T" (U+0166 LATIN CAPITAL LETTER T WITH STROKE) is somewhat related to "T" (as the name suggests) but is used to represent "F".
  • "?" (U+0E04 THAI CHARACTER KHO KHWAI) is not related to any latin character at all and in your example is used to represent "a"

How to make a new List in Java

The following are some ways you can create lists.

  • This will create a list with fixed size, adding/removing elements is not possible, it will throw a java.lang.UnsupportedOperationException if you try to do so.

    List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});
    


  • The following version is a simple list where you can add/remove any number of elements.

    List<String> list = new ArrayList<>();
    


  • This is how to create a LinkedList in java, If you need to do frequent insertion/deletion of elements on the list, you should use LinkedList instead of ArrayList

    List<String> linkedList = new LinkedList<>();
    

How to clear text area with a button in html using javascript?

You need to attach a click event handler and clear the contents of the textarea from that handler.

HTML

<input type="button" value="Clear" id="clear"> 
<textarea id='output' rows=20 cols=90></textarea>

JS

var input = document.querySelector('#clear');
var textarea = document.querySelector('#output');

input.addEventListener('click', function () {
    textarea.value = '';
}, false);

and here's the working demo.

Multiple files upload (Array) with CodeIgniter 2.0

You should use this library for multi upload in CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload

Installation Simply copy the MY_Upload.php file to your applications library directory.

Use: function test_up in controller

public function test_up(){
if($this->input->post('submit')){
    $path = './public/test_upload/';
    $this->load->library('upload');
    $this->upload->initialize(array(
        "upload_path"=>$path,
        "allowed_types"=>"*"
    ));
    if($this->upload->do_multi_upload("myfile")){
        echo '<pre>';
        print_r($this->upload->get_multi_upload_data());
        echo '</pre>';
    }
}else{
    $this->load->view('test/upload_view');
}

}

upload_view.php in applications/view/test folder

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile[]" id="myfile" multiple>
<input type="submit" name="submit" id="submit" value="submit"/>

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

Method 1:\

add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables enter image description here

Method 2: (if method 1 not work then)

simple open command prompt with "run as administrator"

How to add double quotes to a string that is inside a variable?

You could use &quot; instead of ". It will be displayed correctly by the browser.

Detect when input has a 'readonly' attribute

Check the current value of your "readonly" attribute, if it's "false" (a string) or empty (undefined or "") then it's not readonly.

$('input').each(function() {
    var readonly = $(this).attr("readonly");
    if(readonly && readonly.toLowerCase()!=='false') { // this is readonly
        alert('this is a read only field');
    }
});

How to hide elements without having them take space on the page?

To use display:none is a good option just to removing an element BUT it will be also removed for screenreaders. There are also discussions if it effects SEO. There's a good, short article on that topic on A List Apart

If you really just want hide and not remove an element, better use:

div {
  position: absolute; 
  left: -999em;
}

Like this it can be also read by screen readers.

The only disadvantage of this method is, that this DIV is actually rendered and it might effect the performance, especially on mobile phones.

Git commit with no commit message

When working on an important code update, if you really need an intermediate safepoint you might just do:

git commit -am'.'

or shorter:

git commit -am.

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I solved this by assigning a ref to the component and then checking if the ref exists before setting the state:

myMethod(){
  if (this.refs.myRef) 
   this.setState({myVar: true});
}

render() {
  return (
    <div ref="myRef">
      {this.state.myVar}
    </div>
  );
}

And lately, since I am using mostly functional components, I am using this pattern:

const Component = () => {
  const ref = React.useRef(null);
  const [count, setCount] = React.useState(0);

  const increment = () => {
    setTimeout(() => { // usually fetching API data here
      if (ref.current !== null) {
        setCount((count) => count + 1);
      }
    }, 100);
  };

  return (
    <button onClick={increment} ref={ref}>
      Async Increment {count}
    </button>
  );
};

How can I match a string with a regex in Bash?

I don't have enough rep to comment here, so I'm submitting a new answer to improve on dogbane's answer. The dot . in the regexp

[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched

will actually match any character, not only the literal dot between 'tar.bz2', for example

[[ sed-4.2.2.tar4bz2 =~ tar.bz2$ ]] && echo matched
[[ sed-4.2.2.tar§bz2 =~ tar.bz2$ ]] && echo matched

or anything that doesn't require escaping with '\'. The strict syntax should then be

[[ sed-4.2.2.tar.bz2 =~ tar\.bz2$ ]] && echo matched

or you can go even stricter and also include the previous dot in the regex:

[[ sed-4.2.2.tar.bz2 =~ \.tar\.bz2$ ]] && echo matched

Get current NSDate in timestamp format

use [[NSDate date] timeIntervalSince1970]

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I believe this is help full for who are getting this below Exception on to pumping data through logstash Error: logstash.inputs.jdbc - Exception when executing JDBC query {:exception=>#}

Answer:jdbc:mysql://localhost:3306/database_name?zeroDateTimeBehavior=convertToNull"

or if you are working with mysql

jQuery: Handle fallback for failed AJAX Request

I believe that what you are looking for is error option for the jquery ajax object

getJSON is a wrapper to the $.ajax object, but it doesn't provide you with access to the error option.

EDIT: dcneiner has given a good example of the code you would need to use. (Even before I could post my reply)

Specifying a custom DateTime format when serializing with Json.Net

There is another solution I've been using. Just create a string property and use it for json. This property wil return date properly formatted.

class JSonModel {
    ...

    [JsonIgnore]
    public DateTime MyDate { get; set; }

    [JsonProperty("date")]
    public string CustomDate {
        get { return MyDate.ToString("ddMMyyyy"); }
        // set { MyDate = DateTime.Parse(value); }
        set { MyDate = DateTime.ParseExact(value, "ddMMyyyy", null); }
    }

    ...
}

This way you don't have to create extra classes. Also, it allows you to create diferent data formats. e.g, you can easily create another Property for Hour using the same DateTime.

Value does not fall within the expected range

This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.

If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.

Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception

Cheers,

Android button with icon and text

For anyone looking to do this dynamically then setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) on the buttons object will assist.

Sample

Button search = (Button) findViewById(R.id.yoursearchbutton);
search.setCompoundDrawables('your_drawable',null,null,null);

How to pass values across the pages in ASP.net without using Session

If it's just for passing values between pages and you only require it for the one request. Use Context.

Context

The Context object holds data for a single user, for a single request, and it is only persisted for the duration of the request. The Context container can hold large amounts of data, but typically it is used to hold small pieces of data because it is often implemented for every request through a handler in the global.asax. The Context container (accessible from the Page object or using System.Web.HttpContext.Current) is provided to hold values that need to be passed between different HttpModules and HttpHandlers. It can also be used to hold information that is relevant for an entire request. For example, the IBuySpy portal stuffs some configuration information into this container during the Application_BeginRequest event handler in the global.asax. Note that this only applies during the current request; if you need something that will still be around for the next request, consider using ViewState. Setting and getting data from the Context collection uses syntax identical to what you have already seen with other collection objects, like the Application, Session, and Cache. Two simple examples are shown here:

// Add item to
Context Context.Items["myKey"] = myValue;

// Read an item from the
 Context Response.Write(Context["myKey"]);

http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S6

Using the above. If you then do a Server.Transfer the data you've saved in the context will now be available to the next page. You don't have to concern yourself with removing/tidying up this data as it is only scoped to the current request.

Listing all the folders subfolders and files in a directory using php

In case you want to use directoryIterator

Following function is a re-implementation of @Shef answer with directoryIterator

function listFolderFiles($dir)
{
    echo '<ol>';
    foreach (new DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
            echo '<li>' . $fileInfo->getFilename();
            if ($fileInfo->isDir()) {
                listFolderFiles($fileInfo->getPathname());
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}
listFolderFiles('Main Dir');

CSS Equivalent of the "if" statement

No. But can you give an example what you have in mind? What condition do you want to check?

Maybe Sass or Compass are interesting for you.

Quote from Sass:

Sass makes CSS fun again. Sass is CSS, plus nested rules, variables, mixins, and more, all in a concise, readable syntax.

Angular 2 TypeScript how to find element in Array

You could combine .find with arrow functions and destructuring. Take this example from MDN.

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }

Decimal separator comma (',') with numberDecimal inputType in EditText

IMHO the best approach for this problem is to just use the InputFilter. A nice gist is here DecimalDigitsInputFilter. Then you can just:

editText.setInputType(TYPE_NUMBER_FLAG_DECIMAL | TYPE_NUMBER_FLAG_SIGNED | TYPE_CLASS_NUMBER)
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789,.-"))
editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});

How to continue the code on the next line in VBA

To have newline in code you use _

Example:

Dim a As Integer
a = 500 _
  + 80 _
  + 90

MsgBox a

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Here is My Code

protected void btnExcel_Click(object sender, ImageClickEventArgs e)
    {
        if (gvDetail.Rows.Count > 0)
        {
            System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
            gvDetail.RenderControl(htmlWrite1);

            gvDetail.AllowPaging = false;
            Search();
            sh.ExportToExcel(gvDetail, "Report");
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

Java Map equivalent in C#

You can index Dictionary, you didn't need 'get'.

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

An efficient way to test/get values is TryGetValue (thanx to Earwicker):

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

With this method you can fast and exception-less get values (if present).

Resources:

Dictionary-Keys

Try Get Value

convert epoch time to date

EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:

import java.util.*;
import java.text.*;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Date date = new Date(1318386508000L);
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
        String formatted = format.format(date);
        System.out.println(formatted);
        format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
        formatted = format.format(date);
        System.out.println(formatted);
    }
}

Output:

12/10/2011 02:28:28
12/10/2011 13:28:28

I would also suggest you start using Joda Time which is simply a much nicer date/time API...

EDIT: Note that if your system doesn't know about the Australia/Sydney time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah") it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName() and see what it says... and check your code for typos too :)

How to change indentation in Visual Studio Code?

You can change this in global User level or Workspace level.

Open the settings: Using the shortcut Ctrl , or clicking File > Preferences > Settings as shown below.

Settings on VS Code menu

Then, do the following 2 changes: (type tabSize in the search bar)

  1. Uncheck the checkbox of Detect Indentation
  2. Change the tab size to be 2/4 (Although I strongly think 2 is correct for JS :))

enter image description here

Why is it OK to return a 'vector' from a function?

Can we guarantee it will not die?

As long there is no reference returned, it's perfectly fine to do so. words will be moved to the variable receiving the result.

The local variable will go out of scope. after it was moved (or copied).

Descending order by date filter in AngularJs

You can prefix the argument in orderBy with a '-' to have descending order instead of ascending. I would write it like this:

<div class="recent" 
   ng-repeat="reader in book.reader | orderBy: '-created_at' | limitTo: 1">
</div>

This is also stated in the documentation for the filter orderBy.

How to get current class name including package name in Java?

The fully-qualified name is opbtained as follows:

String fqn = YourClass.class.getName();

But you need to read a classpath resource. So use

InputStream in = YourClass.getResourceAsStream("resource.txt");

SQL to Entity Framework Count Group-By

Edit: EF Core 2.1 finally supports GroupBy

But always look out in the console / log for messages. If you see a notification that your query could not be converted to SQL and will be evaluated locally then you may need to rewrite it.


Entity Framework 7 (now renamed to Entity Framework Core 1.0 / 2.0) does not yet support GroupBy() for translation to GROUP BY in generated SQL (even in the final 1.0 release it won't). Any grouping logic will run on the client side, which could cause a lot of data to be loaded.

Eventually code written like this will automagically start using GROUP BY, but for now you need to be very cautious if loading your whole un-grouped dataset into memory will cause performance issues.

For scenarios where this is a deal-breaker you will have to write the SQL by hand and execute it through EF.

If in doubt fire up Sql Profiler and see what is generated - which you should probably be doing anyway.

https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

MDPI - 32px
HDPI - 48px
XHDPI- 64px

This Cheat Sheet might be handy for you. check the image :-)

image

CSS transition with visibility not working

Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337

You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0 only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden, you can eliminate this problem:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:20px;_x000D_
}_x000D_
.menu {_x000D_
    visibility:hidden;_x000D_
    opacity:0;_x000D_
    transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
    _x000D_
    background:#eee;_x000D_
    width:100px;_x000D_
    margin:0;_x000D_
    padding:5px;_x000D_
    list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
    visibility:visible;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="#">Open Menu</a>_x000D_
  <ul class="menu">_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Apache is downloading php files instead of displaying them

Ok... I know that there are 1.000.000 answers to this questions already, - but I have spent at least 6 effective hours, figuring this one out; and I have googled it hundreds of times and not found a single post about it. So I figured that I would add the solution to my problem here.

The conclusion

If I commented these two lines out in my .conf-files in the /etc/apache2/[[SERVER-NAME].conf-file:

php_admin_value engine Off
IPCComTimeout 31

I have no idea what they do or how they got there, - but it is in every one of my .conf-files. And if I remove those lines and ensure that there is a symlink in /etc/apache2/sites-enabled/-folder, then it doesn't download the index.php - and every works as it should.

The entire story

I have VirtualMin installed on an Ubuntu 16.04 VPS. I upgraded to PHP version 7.2. Shortly after that, I updated the Ubuntu-version and struck a 'Kernel Offset: Disabled'-error. So I had to go delete the latest Ubuntu-version, - and when my OS booted up again: BOOM! I got the error that his post talks about: For every site on my VPS, it simply downloaded the index.php instead of showing it.

I tried all kinds of stuff:

  • Removed PHP7.2 and installed PHP5.6 (I know now, that the PHP-version has nothing to do with it; it's the apache-configuration that needs work).
  • Tried enabling and disabling apache modules, on the existing installation, but without luck.
  • Then I removed apache completely and installed it again, where-after the problem was still there!
  • Tried playing around with the Virutal Server setup in VirtualMin ( Webmin >> Servers >> Apache Webserver ).
  • Checked the configuration on a single Virtual-server ( Virtualmin >> System Settings >> Re-Check Configuration )... This step was pretty nice, since it told which module in Apache was missing; where-after I could enable it with a2enmod [MODULE_NAME]. And I found the module name by Googling around. I had to active about 6-8 modules, before I got past that step in the validation - and it took a couple of minutes before the cache ran out, - so doing this was a tedious step.
  • And lastly, I figured out above-written conclusion - together with the symlinks, - and then I got it to work. I had to go through it for every site on my VPS, though.

Vertical (rotated) text in HTML table

I was using the Font Awesome library and was able to achieve this affect by tacking on the following to any html element.

<div class="fa fa-rotate-270">
  My Test Text
</div>

Your mileage may vary.

CSS horizontal scroll

try using table structure, it's more back compatible. Check this outHorizontal Scrolling using Tables

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

solution to wait for several subprocesses and to exit when any one of them exits with non-zero status code is by using 'wait -n'

#!/bin/bash
wait_for_pids()
{
    for (( i = 1; i <= $#; i++ )) do
        wait -n $@
        status=$?
        echo "received status: "$status
        if [ $status -ne 0 ] && [ $status -ne 127 ]; then
            exit 1
        fi
    done
}

sleep_for_10()
{
    sleep 10
    exit 10
}

sleep_for_20()
{
    sleep 20
}

sleep_for_10 &
pid1=$!

sleep_for_20 &
pid2=$!

wait_for_pids $pid2 $pid1

status code '127' is for non-existing process which means the child might have exited.

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

For me the problem was very strange.
I have a testng.xml file at the root of my Eclipse project. When I changed the file through Eclipse, it wasn't changing the testng.xml file in my directory.

Turns out it made a copy of the folder into the eclipse workspace..

Hope this helps someone out

Using "Object.create" instead of "new"

The advantage is that Object.create is typically slower than new on most browsers

In this jsperf example, in a Chromium, browser new is 30 times as fast as Object.create(obj) although both are pretty fast. This is all pretty strange because new does more things (like invoking a constructor) where Object.create should be just creating a new Object with the passed in object as a prototype (secret link in Crockford-speak)

Perhaps the browsers have not caught up in making Object.create more efficient (perhaps they are basing it on new under the covers ... even in native code)

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

If AJAX isn't an option you can use nested data structures to simplify.

<?php
$var = array(
    'qwe' => 'asd',
    'asd' => array(
        1 => 2,
        3 => 4,
    ),
    'zxc' => 0,
);
?>
<script>var data = <?php echo json_encode($var); ?>;</script>

How can I use Python to get the system hostname?

I needed the name of the PC to use in my PyLog conf file, and the socket library is not available, but os library is.

For Windows I used:

os.getenv('COMPUTERNAME', 'defaultValue')

Where defaultValue is a string to prevent None being returned

Is there a way to detect if an image is blurry?

During some work with an auto-focus lens, I came across this very useful set of algorithms for detecting image focus. It's implemented in MATLAB, but most of the functions are quite easy to port to OpenCV with filter2D.

It's basically a survey implementation of many focus measurement algorithms. If you want to read the original papers, references to the authors of the algorithms are provided in the code. The 2012 paper by Pertuz, et al. Analysis of focus measure operators for shape from focus (SFF) gives a great review of all of these measure as well as their performance (both in terms of speed and accuracy as applied to SFF).

EDIT: Added MATLAB code just in case the link dies.

function FM = fmeasure(Image, Measure, ROI)
%This function measures the relative degree of focus of 
%an image. It may be invoked as:
%
%   FM = fmeasure(Image, Method, ROI)
%
%Where 
%   Image,  is a grayscale image and FM is the computed
%           focus value.
%   Method, is the focus measure algorithm as a string.
%           see 'operators.txt' for a list of focus 
%           measure methods. 
%   ROI,    Image ROI as a rectangle [xo yo width heigth].
%           if an empty argument is passed, the whole
%           image is processed.
%
%  Said Pertuz
%  Abr/2010


if ~isempty(ROI)
    Image = imcrop(Image, ROI);
end

WSize = 15; % Size of local window (only some operators)

switch upper(Measure)
    case 'ACMO' % Absolute Central Moment (Shirvaikar2004)
        if ~isinteger(Image), Image = im2uint8(Image);
        end
        FM = AcMomentum(Image);

    case 'BREN' % Brenner's (Santos97)
        [M N] = size(Image);
        DH = Image;
        DV = Image;
        DH(1:M-2,:) = diff(Image,2,1);
        DV(:,1:N-2) = diff(Image,2,2);
        FM = max(DH, DV);        
        FM = FM.^2;
        FM = mean2(FM);

    case 'CONT' % Image contrast (Nanda2001)
        ImContrast = inline('sum(abs(x(:)-x(5)))');
        FM = nlfilter(Image, [3 3], ImContrast);
        FM = mean2(FM);

    case 'CURV' % Image Curvature (Helmli2001)
        if ~isinteger(Image), Image = im2uint8(Image);
        end
        M1 = [-1 0 1;-1 0 1;-1 0 1];
        M2 = [1 0 1;1 0 1;1 0 1];
        P0 = imfilter(Image, M1, 'replicate', 'conv')/6;
        P1 = imfilter(Image, M1', 'replicate', 'conv')/6;
        P2 = 3*imfilter(Image, M2, 'replicate', 'conv')/10 ...
            -imfilter(Image, M2', 'replicate', 'conv')/5;
        P3 = -imfilter(Image, M2, 'replicate', 'conv')/5 ...
            +3*imfilter(Image, M2, 'replicate', 'conv')/10;
        FM = abs(P0) + abs(P1) + abs(P2) + abs(P3);
        FM = mean2(FM);

    case 'DCTE' % DCT energy ratio (Shen2006)
        FM = nlfilter(Image, [8 8], @DctRatio);
        FM = mean2(FM);

    case 'DCTR' % DCT reduced energy ratio (Lee2009)
        FM = nlfilter(Image, [8 8], @ReRatio);
        FM = mean2(FM);

    case 'GDER' % Gaussian derivative (Geusebroek2000)        
        N = floor(WSize/2);
        sig = N/2.5;
        [x,y] = meshgrid(-N:N, -N:N);
        G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig);
        Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:));
        Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:));
        Rx = imfilter(double(Image), Gx, 'conv', 'replicate');
        Ry = imfilter(double(Image), Gy, 'conv', 'replicate');
        FM = Rx.^2+Ry.^2;
        FM = mean2(FM);

    case 'GLVA' % Graylevel variance (Krotkov86)
        FM = std2(Image);

    case 'GLLV' %Graylevel local variance (Pech2000)        
        LVar = stdfilt(Image, ones(WSize,WSize)).^2;
        FM = std2(LVar)^2;

    case 'GLVN' % Normalized GLV (Santos97)
        FM = std2(Image)^2/mean2(Image);

    case 'GRAE' % Energy of gradient (Subbarao92a)
        Ix = Image;
        Iy = Image;
        Iy(1:end-1,:) = diff(Image, 1, 1);
        Ix(:,1:end-1) = diff(Image, 1, 2);
        FM = Ix.^2 + Iy.^2;
        FM = mean2(FM);

    case 'GRAT' % Thresholded gradient (Snatos97)
        Th = 0; %Threshold
        Ix = Image;
        Iy = Image;
        Iy(1:end-1,:) = diff(Image, 1, 1);
        Ix(:,1:end-1) = diff(Image, 1, 2);
        FM = max(abs(Ix), abs(Iy));
        FM(FM<Th)=0;
        FM = sum(FM(:))/sum(sum(FM~=0));

    case 'GRAS' % Squared gradient (Eskicioglu95)
        Ix = diff(Image, 1, 2);
        FM = Ix.^2;
        FM = mean2(FM);

    case 'HELM' %Helmli's mean method (Helmli2001)        
        MEANF = fspecial('average',[WSize WSize]);
        U = imfilter(Image, MEANF, 'replicate');
        R1 = U./Image;
        R1(Image==0)=1;
        index = (U>Image);
        FM = 1./R1;
        FM(index) = R1(index);
        FM = mean2(FM);

    case 'HISE' % Histogram entropy (Krotkov86)
        FM = entropy(Image);

    case 'HISR' % Histogram range (Firestone91)
        FM = max(Image(:))-min(Image(:));


    case 'LAPE' % Energy of laplacian (Subbarao92a)
        LAP = fspecial('laplacian');
        FM = imfilter(Image, LAP, 'replicate', 'conv');
        FM = mean2(FM.^2);

    case 'LAPM' % Modified Laplacian (Nayar89)
        M = [-1 2 -1];        
        Lx = imfilter(Image, M, 'replicate', 'conv');
        Ly = imfilter(Image, M', 'replicate', 'conv');
        FM = abs(Lx) + abs(Ly);
        FM = mean2(FM);

    case 'LAPV' % Variance of laplacian (Pech2000)
        LAP = fspecial('laplacian');
        ILAP = imfilter(Image, LAP, 'replicate', 'conv');
        FM = std2(ILAP)^2;

    case 'LAPD' % Diagonal laplacian (Thelen2009)
        M1 = [-1 2 -1];
        M2 = [0 0 -1;0 2 0;-1 0 0]/sqrt(2);
        M3 = [-1 0 0;0 2 0;0 0 -1]/sqrt(2);
        F1 = imfilter(Image, M1, 'replicate', 'conv');
        F2 = imfilter(Image, M2, 'replicate', 'conv');
        F3 = imfilter(Image, M3, 'replicate', 'conv');
        F4 = imfilter(Image, M1', 'replicate', 'conv');
        FM = abs(F1) + abs(F2) + abs(F3) + abs(F4);
        FM = mean2(FM);

    case 'SFIL' %Steerable filters (Minhas2009)
        % Angles = [0 45 90 135 180 225 270 315];
        N = floor(WSize/2);
        sig = N/2.5;
        [x,y] = meshgrid(-N:N, -N:N);
        G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig);
        Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:));
        Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:));
        R(:,:,1) = imfilter(double(Image), Gx, 'conv', 'replicate');
        R(:,:,2) = imfilter(double(Image), Gy, 'conv', 'replicate');
        R(:,:,3) = cosd(45)*R(:,:,1)+sind(45)*R(:,:,2);
        R(:,:,4) = cosd(135)*R(:,:,1)+sind(135)*R(:,:,2);
        R(:,:,5) = cosd(180)*R(:,:,1)+sind(180)*R(:,:,2);
        R(:,:,6) = cosd(225)*R(:,:,1)+sind(225)*R(:,:,2);
        R(:,:,7) = cosd(270)*R(:,:,1)+sind(270)*R(:,:,2);
        R(:,:,7) = cosd(315)*R(:,:,1)+sind(315)*R(:,:,2);
        FM = max(R,[],3);
        FM = mean2(FM);

    case 'SFRQ' % Spatial frequency (Eskicioglu95)
        Ix = Image;
        Iy = Image;
        Ix(:,1:end-1) = diff(Image, 1, 2);
        Iy(1:end-1,:) = diff(Image, 1, 1);
        FM = mean2(sqrt(double(Iy.^2+Ix.^2)));

    case 'TENG'% Tenengrad (Krotkov86)
        Sx = fspecial('sobel');
        Gx = imfilter(double(Image), Sx, 'replicate', 'conv');
        Gy = imfilter(double(Image), Sx', 'replicate', 'conv');
        FM = Gx.^2 + Gy.^2;
        FM = mean2(FM);

    case 'TENV' % Tenengrad variance (Pech2000)
        Sx = fspecial('sobel');
        Gx = imfilter(double(Image), Sx, 'replicate', 'conv');
        Gy = imfilter(double(Image), Sx', 'replicate', 'conv');
        G = Gx.^2 + Gy.^2;
        FM = std2(G)^2;

    case 'VOLA' % Vollath's correlation (Santos97)
        Image = double(Image);
        I1 = Image; I1(1:end-1,:) = Image(2:end,:);
        I2 = Image; I2(1:end-2,:) = Image(3:end,:);
        Image = Image.*(I1-I2);
        FM = mean2(Image);

    case 'WAVS' %Sum of Wavelet coeffs (Yang2003)
        [C,S] = wavedec2(Image, 1, 'db6');
        H = wrcoef2('h', C, S, 'db6', 1);   
        V = wrcoef2('v', C, S, 'db6', 1);   
        D = wrcoef2('d', C, S, 'db6', 1);   
        FM = abs(H) + abs(V) + abs(D);
        FM = mean2(FM);

    case 'WAVV' %Variance of  Wav...(Yang2003)
        [C,S] = wavedec2(Image, 1, 'db6');
        H = abs(wrcoef2('h', C, S, 'db6', 1));
        V = abs(wrcoef2('v', C, S, 'db6', 1));
        D = abs(wrcoef2('d', C, S, 'db6', 1));
        FM = std2(H)^2+std2(V)+std2(D);

    case 'WAVR'
        [C,S] = wavedec2(Image, 3, 'db6');
        H = abs(wrcoef2('h', C, S, 'db6', 1));   
        V = abs(wrcoef2('v', C, S, 'db6', 1));   
        D = abs(wrcoef2('d', C, S, 'db6', 1)); 
        A1 = abs(wrcoef2('a', C, S, 'db6', 1));
        A2 = abs(wrcoef2('a', C, S, 'db6', 2));
        A3 = abs(wrcoef2('a', C, S, 'db6', 3));
        A = A1 + A2 + A3;
        WH = H.^2 + V.^2 + D.^2;
        WH = mean2(WH);
        WL = mean2(A);
        FM = WH/WL;
    otherwise
        error('Unknown measure %s',upper(Measure))
end
 end
%************************************************************************
function fm = AcMomentum(Image)
[M N] = size(Image);
Hist = imhist(Image)/(M*N);
Hist = abs((0:255)-255*mean2(Image))'.*Hist;
fm = sum(Hist);
end

%******************************************************************
function fm = DctRatio(M)
MT = dct2(M).^2;
fm = (sum(MT(:))-MT(1,1))/MT(1,1);
end

%************************************************************************
function fm = ReRatio(M)
M = dct2(M);
fm = (M(1,2)^2+M(1,3)^2+M(2,1)^2+M(2,2)^2+M(3,1)^2)/(M(1,1)^2);
end
%******************************************************************

A few examples of OpenCV versions:

// OpenCV port of 'LAPM' algorithm (Nayar89)
double modifiedLaplacian(const cv::Mat& src)
{
    cv::Mat M = (Mat_<double>(3, 1) << -1, 2, -1);
    cv::Mat G = cv::getGaussianKernel(3, -1, CV_64F);

    cv::Mat Lx;
    cv::sepFilter2D(src, Lx, CV_64F, M, G);

    cv::Mat Ly;
    cv::sepFilter2D(src, Ly, CV_64F, G, M);

    cv::Mat FM = cv::abs(Lx) + cv::abs(Ly);

    double focusMeasure = cv::mean(FM).val[0];
    return focusMeasure;
}

// OpenCV port of 'LAPV' algorithm (Pech2000)
double varianceOfLaplacian(const cv::Mat& src)
{
    cv::Mat lap;
    cv::Laplacian(src, lap, CV_64F);

    cv::Scalar mu, sigma;
    cv::meanStdDev(lap, mu, sigma);

    double focusMeasure = sigma.val[0]*sigma.val[0];
    return focusMeasure;
}

// OpenCV port of 'TENG' algorithm (Krotkov86)
double tenengrad(const cv::Mat& src, int ksize)
{
    cv::Mat Gx, Gy;
    cv::Sobel(src, Gx, CV_64F, 1, 0, ksize);
    cv::Sobel(src, Gy, CV_64F, 0, 1, ksize);

    cv::Mat FM = Gx.mul(Gx) + Gy.mul(Gy);

    double focusMeasure = cv::mean(FM).val[0];
    return focusMeasure;
}

// OpenCV port of 'GLVN' algorithm (Santos97)
double normalizedGraylevelVariance(const cv::Mat& src)
{
    cv::Scalar mu, sigma;
    cv::meanStdDev(src, mu, sigma);

    double focusMeasure = (sigma.val[0]*sigma.val[0]) / mu.val[0];
    return focusMeasure;
}

No guarantees on whether or not these measures are the best choice for your problem, but if you track down the papers associated with these measures, they may give you more insight. Hope you find the code useful! I know I did.

Python idiom to return first item or None

def head(iterable):
    try:
        return iter(iterable).next()
    except StopIteration:
        return None

print head(xrange(42, 1000)  # 42
print head([])               # None

BTW: I'd rework your general program flow into something like this:

lists = [
    ["first", "list"],
    ["second", "list"],
    ["third", "list"]
]

def do_something(element):
    if not element:
        return
    else:
        # do something
        pass

for li in lists:
    do_something(head(li))

(Avoiding repetition whenever possible)

How to vertically center content with variable height within a div?

Best result for me so far:

div to be centered:

position: absolute;
top: 50%;
transform: translateY(-50%);
margin: 0 auto;
right: 0;
left: 0;

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Save Screen (program) output to a file

The following command works for Screen version 4.06.02:

screen -L -Logfile Log_file_name_of_your_choice command_to_be_executed

From the man page of Screen:

-Logfile file : By default logfile name is "screenlog.0".
                You can set new logfile name with the "-Logfile" option.

You can check the existing version of Screen using screen -version. You can download and install the latest Screen version from https://www.gnu.org/software/screen/.

How to set iframe size dynamically

If you use jquery, it can be done by using $(window).height();

<iframe src="html_intro.asp" width="100%" class="myIframe">
<p>Hi SOF</p>
</iframe>

<script type="text/javascript" language="javascript"> 
$('.myIframe').css('height', $(window).height()+'px');
</script>

JQuery Validate Dropdown list

I have modified your code a little. Here's a working version (for me):

    <select name="dd1" id="dd1">
       <option value="none">None</option>
       <option value="o1">option 1</option>
       <option value="o2">option 2</option>
       <option value="o3">option 3</option>
    </select>  
    <div style="color:red;" id="msg_id"></div>

<script>
    $('#everything').submit(function(e){ 
        var department = $("#msg_id");
        var msg = "Please select Department";
            if ($('#dd1').val() == "") {
                department.append(msg);
                e.preventDefault();
                return false;
            }
        });
 </script>

Selecting last element in JavaScript array

var last = function( obj, key ) { 
    var a = obj[key];
    return a[a.length - 1];
};

last(loc, 'f096012e-2497-485d-8adb-7ec0b9352c52');

Why does overflow:hidden not work in a <td>?

Here is the same problem.

You need to set table-layout:fixed and a suitable width on the table element, as well as overflow:hidden and white-space: nowrap on the table cells.


Examples

Fixed width columns

The width of the table has to be the same (or smaller) than the fixed width cell(s).

With one fixed width column:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
  max-width: 100px;
}
td {
  background: #F00;
  padding: 20px;
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
  border: solid 1px #000;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

With multiple fixed width columns:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
  max-width: 200px;
}
td {
  background: #F00;
  padding: 20px;
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
  border: solid 1px #000;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Fixed and fluid width columns

A width for the table must be set, but any extra width is simply taken by the fluid cell(s).

With multiple columns, fixed width and fluid width:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
}
td {
  background: #F00;
  padding: 20px;
  border: solid 1px #000;
}
tr td:first-child {
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

How to rsync only a specific list of files?

There is a flag --files-from that does exactly what you want. From man rsync:

--files-from=FILE

Using this option allows you to specify the exact list of files to transfer (as read from the specified FILE or - for standard input). It also tweaks the default behavior of rsync to make transferring just the specified files and directories easier:

  • The --relative (-R) option is implied, which preserves the path information that is specified for each item in the file (use --no-relative or --no-R if you want to turn that off).

  • The --dirs (-d) option is implied, which will create directories specified in the list on the destination rather than noisily skipping them (use --no-dirs or --no-d if you want to turn that off).

  • The --archive (-a) option’s behavior does not imply --recursive (-r), so specify it explicitly, if you want it.

  • These side-effects change the default state of rsync, so the position of the --files-from option on the command-line has no bearing on how other options are parsed (e.g. -a works the same before or after --files-from, as does --no-R and all other options).

The filenames that are read from the FILE are all relative to the source dir -- any leading slashes are removed and no ".." references are allowed to go higher than the source dir. For example, take this command:

rsync -a --files-from=/tmp/foo /usr remote:/backup

If /tmp/foo contains the string "bin" (or even "/bin"), the /usr/bin directory will be created as /backup/bin on the remote host. If it contains "bin/" (note the trailing slash), the immediate contents of the directory would also be sent (without needing to be explicitly mentioned in the file -- this began in version 2.6.4). In both cases, if the -r option was enabled, that dir’s entire hierarchy would also be transferred (keep in mind that -r needs to be specified explicitly with --files-from, since it is not implied by -a). Also note that the effect of the (enabled by default) --relative option is to duplicate only the path info that is read from the file -- it does not force the duplication of the source-spec path (/usr in this case).

In addition, the --files-from file can be read from the remote host instead of the local host if you specify a "host:" in front of the file (the host must match one end of the transfer). As a short-cut, you can specify just a prefix of ":" to mean "use the remote end of the transfer". For example:

rsync -a --files-from=:/path/file-list src:/ /tmp/copy

This would copy all the files specified in the /path/file-list file that was located on the remote "src" host.

If the --iconv and --protect-args options are specified and the --files-from filenames are being sent from one host to another, the filenames will be translated from the sending host’s charset to the receiving host’s charset.

NOTE: sorting the list of files in the --files-from input helps rsync to be more efficient, as it will avoid re-visiting the path elements that are shared between adjacent entries. If the input is not sorted, some path elements (implied directories) may end up being scanned multiple times, and rsync will eventually unduplicate them after they get turned into file-list elements.

SQL - HAVING vs. WHERE

WHERE clause introduces a condition on individual rows; HAVING clause introduces a condition on aggregations, i.e. results of selection where a single result, such as count, average, min, max, or sum, has been produced from multiple rows. Your query calls for a second kind of condition (i.e. a condition on an aggregation) hence HAVING works correctly.

As a rule of thumb, use WHERE before GROUP BY and HAVING after GROUP BY. It is a rather primitive rule, but it is useful in more than 90% of the cases.

While you're at it, you may want to re-write your query using ANSI version of the join:

SELECT  L.LectID, Fname, Lname
FROM Lecturers L
JOIN Lecturers_Specialization S ON L.LectID=S.LectID
GROUP BY L.LectID, Fname, Lname
HAVING COUNT(S.Expertise)>=ALL
(SELECT COUNT(Expertise) FROM Lecturers_Specialization GROUP BY LectID)

This would eliminate WHERE that was used as a theta join condition.

Controlling Spacing Between Table Cells

table.test td {
    background-color: lime;
    padding: 12px;
    border:2px solid #fff;border-collapse:separate;
}

Java array reflection: isArray vs. instanceof

In the latter case, if obj is null you won't get a NullPointerException but a false.

Using Bootstrap Tooltip with AngularJS

Please remember one thing if you want to use bootstrap tooltip in angularjs is order of your scripts if you are using jquery-ui as well, it should be:

  • jQuery
  • jQuery UI
  • Bootstap

It is tried and tested

milliseconds to time in javascript

This is the solution I got and working so good!

function msToHuman(duration) {
var milliseconds = parseInt((duration%1000)/100)
    seconds = parseInt((duration/1000)%60)
    minutes = parseInt((duration/(1000*60))%60)
    hours = parseInt((duration/(1000*60*60))%24);


return hours + "hrs " minutes + "min " + seconds + "sec " + milliseconds + 'ms';
}

How to assign the output of a command to a Makefile variable

With GNU Make, you can use shell and eval to store, run, and assign output from arbitrary command line invocations. The difference between the example below and those which use := is the := assignment happens once (when it is encountered) and for all. Recursively expanded variables set with = are a bit more "lazy"; references to other variables remain until the variable itself is referenced, and the subsequent recursive expansion takes place each time the variable is referenced, which is desirable for making "consistent, callable, snippets". See the manual on setting variables for more info.

# Generate a random number.
# This is not run initially.
GENERATE_ID = $(shell od -vAn -N2 -tu2 < /dev/urandom)

# Generate a random number, and assign it to MY_ID
# This is not run initially.
SET_ID = $(eval MY_ID=$(GENERATE_ID))

# You can use .PHONY to tell make that we aren't building a target output file
.PHONY: mytarget
mytarget:
# This is empty when we begin
    @echo $(MY_ID)
# This recursively expands SET_ID, which calls the shell command and sets MY_ID
    $(SET_ID)
# This will now be a random number
    @echo $(MY_ID)
# Recursively expand SET_ID again, which calls the shell command (again) and sets MY_ID (again)
    $(SET_ID)
# This will now be a different random number
    @echo $(MY_ID)

How to get the onclick calling object?

I think the best way is to use currentTarget property instead of target property.

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred.


For example:

<a href="#"><span class="icon"></span> blah blah</a>

Javascript:

a.addEventListener('click', e => {
    e.currentTarget; // always returns "a" element
    e.target; // may return "a" or "span"
})

Node.js Write a line into a .txt file

Step 1

If you have a small file Read all the file data in to memory

Step 2

Convert file data string into Array

Step 3

Search the array to find a location where you want to insert the text

Step 4

Once you have the location insert your text

yourArray.splice(index,0,"new added test");

Step 5

convert your array to string

yourArray.join("");

Step 6

write your file like so

fs.createWriteStream(yourArray);

This is not advised if your file is too big

how to get request path with express req object

In some cases you should use:

req.path

This gives you the path, instead of the complete requested URL. For example, if you are only interested in which page the user requested and not all kinds of parameters the url:

/myurl.htm?allkinds&ofparameters=true

req.path will give you:

/myurl.html

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

Ruby combining an array into one string

While a bit more cryptic than join, you can also multiply the array by a string.

@arr * " "

How to initialize static variables

Instead of finding a way to get static variables working, I prefer to simply create a getter function. Also helpful if you need arrays belonging to a specific class, and a lot simpler to implement.

class MyClass
{
   public static function getTypeList()
   {
       return array(
           "type_a"=>"Type A",
           "type_b"=>"Type B",
           //... etc.
       );
   }
}

Wherever you need the list, simply call the getter method. For example:

if (array_key_exists($type, MyClass::getTypeList()) {
     // do something important...
}

String Array object in Java

I think you are a little messed up with what you doing. Athlete is an object, athlete has a name, i has a city where he lives. Athlete can dive.

public class Athlete {

private String name;
private String city;

public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){} 
}




public class Main{
public static void main (String [] args){

String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord

--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);

}
}

How to hide action bar before activity is created, and then show it again?

you can use this :

getSupportActionBar().hide(); if it doesn't work try this one :

getActionBar().hide();

if above doesn't work try like this :

in your directory = res/values/style.xml , open style.xml -> there is attribute parent change to parent="Theme.AppCompat.Light.DarkActionBar"

if all of it doesn't work too. i don't know anymore. but for me it works.

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

Get week number (in the year) from a date PHP

I have tried to solve this question for years now, I thought I found a shorter solution but had to come back again to the long story. This function gives back the right ISO week notation:

/**
 * calcweek("2018-12-31") => 1901
 * This function calculates the production weeknumber according to the start on 
 * monday and with at least 4 days in the new year. Given that the $date has
 * the following format Y-m-d then the outcome is and integer.
 *
 * @author M.S.B. Bachus
 *
 * @param date-notation PHP "Y-m-d" showing the data as yyyy-mm-dd
 * @return integer
 **/
function calcweek($date) {
  // 1. Convert input to $year, $month, $day
  $dateset      = strtotime($date);
  $year         = date("Y", $dateset);
  $month        = date("m", $dateset);
  $day          = date("d", $dateset);

  $referenceday = getdate(mktime(0,0,0, $month, $day, $year));
  $jan1day      = getdate(mktime(0,0,0,1,1,$referenceday[year]));

  // 2. check if $year is a  leapyear
  if ( ($year%4==0 && $year%100!=0) || $year%400==0) {
    $leapyear = true;
  } else {
    $leapyear = false;
  }

  // 3. check if $year-1 is a  leapyear
  if ( (($year-1)%4==0 && ($year-1)%100!=0) || ($year-1)%400==0 ) {
    $leapyearprev = true;
  } else {
    $leapyearprev = false;
  }

  // 4. find the dayofyearnumber for y m d
  $mnth = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
  $dayofyearnumber = $day + $mnth[$month-1];
  if ( $leapyear && $month > 2 ) { $dayofyearnumber++; }

  // 5. find the jan1weekday for y (monday=1, sunday=7)
  $yy = ($year-1)%100;
  $c  = ($year-1) - $yy;
  $g  = $yy + intval($yy/4);
  $jan1weekday = 1+((((intval($c/100)%4)*5)+$g)%7);

  // 6. find the weekday for y m d
  $h = $dayofyearnumber + ($jan1weekday-1);
  $weekday = 1+(($h-1)%7);

  // 7. find if y m d falls in yearnumber y-1, weeknumber 52 or 53
  $foundweeknum = false;
  if ( $dayofyearnumber <= (8-$jan1weekday) && $jan1weekday > 4 ) {
    $yearnumber = $year - 1;
    if ( $jan1weekday = 5 || ( $jan1weekday = 6 && $leapyearprev )) {
      $weeknumber = 53;
    } else {
      $weeknumber = 52;
    }
    $foundweeknum = true;
  } else {
    $yearnumber = $year;
  }

  // 8. find if y m d falls in yearnumber y+1, weeknumber 1
  if ( $yearnumber == $year && !$foundweeknum) {
    if ( $leapyear ) {
      $i = 366;
    } else {
      $i = 365;
    }
    if ( ($i - $dayofyearnumber) < (4 - $weekday) ) {
      $yearnumber = $year + 1;
      $weeknumber = 1;
      $foundweeknum = true;
    }
  }

  // 9. find if y m d falls in yearnumber y, weeknumber 1 through 53
  if ( $yearnumber == $year && !$foundweeknum ) {
    $j = $dayofyearnumber + (7 - $weekday) + ($jan1weekday - 1);
    $weeknumber = intval( $j/7 );
    if ( $jan1weekday > 4 ) { $weeknumber--; }
  }

  // 10. output iso week number (YYWW)
  return ($yearnumber-2000)*100+$weeknumber;
}

I found out that my short solution missed the 2018-12-31 as it gave back 1801 instead of 1901. So I had to put in this long version which is correct.

Have a fixed position div that needs to scroll if content overflows

The problem with using height:100% is that it will be 100% of the page instead of 100% of the window (as you would probably expect it to be). This will cause the problem that you're seeing, because the non-fixed content is long enough to include the fixed content with 100% height without requiring a scroll bar. The browser doesn't know/care that you can't actually scroll that bar down to see it

You can use fixed to accomplish what you're trying to do.

.fixed-content {
    top: 0;
    bottom:0;
    position:fixed;
    overflow-y:scroll;
    overflow-x:hidden;
}

This fork of your fiddle shows my fix: http://jsfiddle.net/strider820/84AsW/1/

sqlplus how to find details of the currently connected database session

We can get the details and status of session from below query as:

select ' Sid, Serial#, Aud sid : '|| s.sid||' , '||s.serial#||' , '||
       s.audsid||chr(10)|| '     DB User / OS User : '||s.username||
       '   /   '||s.osuser||chr(10)|| '    Machine - Terminal : '||
       s.machine||'  -  '|| s.terminal||chr(10)||
       '        OS Process Ids : '||
       s.process||' (Client)  '||p.spid||' (Server)'|| chr(10)||
       '   Client Program Name : '||s.program "Session Info"
  from v$process p,v$session s
 where p.addr = s.paddr
   and s.sid = nvl('&SID',s.sid)
   and nvl(s.terminal,' ') = nvl('&Terminal',nvl(s.terminal,' '))
   and s.process = nvl('&Process',s.process)
   and p.spid = nvl('&spid',p.spid)
   and s.username = nvl('&username',s.username)
   and nvl(s.osuser,' ') = nvl('&OSUser',nvl(s.osuser,' '))
   and nvl(s.machine,' ') = nvl('&machine',nvl(s.machine,' '))
   and nvl('&SID',nvl('&TERMINAL',nvl('&PROCESS',nvl('&SPID',nvl('&USERNAME',
       nvl('&OSUSER',nvl('&MACHINE','NO VALUES'))))))) <> 'NO VALUES'
/

For more details: https://ora-data.blogspot.in/2016/11/query-session-details.html

Thanks,

pip: no module named _internal

I just encountered the same problem and in my case, it turns out this is a conflict between the python installation in my virtualenv and the site-wide python (Ubuntu). What solves it for me is to run pip in this way, to force usage of the correct python installation (in my vortualenv):

python3 -m pip install PACKAGE

instead of

pip3 install PACKAGE

I realised this when I tried to follow some of the answers here that suggest re-installing pip and the error output I got was pointing to an existing site-wide python library path although I had activated my virtualenv. Worth trying before deleting and re-installing stuff.

Ruby Hash to array of values

It is as simple as

hash.values
#=> [["a", "b", "c"], ["b", "c"]]

this will return a new array populated with the values from hash

if you want to store that new array do

array_of_values = hash.values
#=> [["a", "b", "c"], ["b", "c"]]

array_of_values
 #=> [["a", "b", "c"], ["b", "c"]]

calling server side event from html button control

On your aspx page define the HTML Button element with the usual suspects: runat, class, title, etc.

If this element is part of a data bound control (i.e.: grid view, etc.) you may want to use CommandName and possibly CommandArgument as attributes. Add your button's content and closing tag.

<button id="cmdAction" 
    runat="server" onserverclick="cmdAction_Click()" 
    class="Button Styles" 
    title="Does something on the server" 
    <!-- for databound controls -->
    CommandName="cmdname"> 
    CommandArgument="args..."
    >
    <!-- content -->
    <span class="ui-icon ..."></span>
    <span class="push">Click Me</span>
</button>

On the code behind page the element would call the handler that would be defined as the element's ID_Click event function.

protected void cmdAction_Click(object sender, EventArgs e)
{
: do something.
}

There are other solutions as in using custom controls, etc. Also note that I am using this live on projects in VS2K8.

Hoping this helps. Enjoy!

Django CSRF Cookie Not Set

I had the same error, in my case adding method_decorator helps:

from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator

method_decorator(csrf_protect)
def post(self, request):
    ...

how to upload a file to my server using html

On top of what the others have already stated, some sort of server-side scripting is necessary in order for the server to read and save the file.

Using PHP might be a good choice, but you're free to use any server-side scripting language. http://www.w3schools.com/php/php_file_upload.asp may be of use on that end.

TypeScript getting error TS2304: cannot find name ' require'

I've yet another answer that builds upon all previous ones that describe npm install @types/node and including node in tsconfig.json / compilerOptions / types.

In my case, I have a base tsConfig.json and a separate one in the Angular application that extends this one:

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "types": []
 },

My problem was the empty types in this tsconfi.app.json - it clobbers the one in the base configuration.

Do I need a content-type header for HTTP GET requests?

The accepted answer is wrong. The quote is correct, the assertion that PUT and POST must have it is incorrect. There is no requirement that PUT or POST actually have additional content. Nor is there a prohibition against GET actually having content.

The RFCs say exactly what they mean .. IFF your side (client OR origin server) will be sending additional content, beyond the HTTP headers, it SHOULD specify a Content-Type header. But note it is allowable to omit the Content-Type and still include content (say, by using a Content-Length header).

What does the question mark and the colon (?: ternary operator) mean in objective-c?

It's just a short form of writing an if-then-else statement. It means the same as the following code:

if(inPseudoEditMode)
  label.frame = kLabelIndentedRect;
else
  label.frame = kLabelRect;

nodejs module.js:340 error: cannot find module

  1. Try npm start in Node.js Command Prompt.
  2. Look at the end of the messages - it gives you the path of log file in "Additional Logging Details ..." something like c:\users\MyUser\npm-debug.log
  3. Open this file in Notepad and find the real address of Node.exe : something like C:\\Program Files\\nodejs\\\\node.exe
  4. Try cd to this path
  5. Call node.exe + <full path to your server file.js>

    Server is listening on port 1337 !
    

Find the smallest positive integer that does not occur in a given sequence

This solution is in c# but complete the test with 100% score

public int solution(int[] A) {
    // write your code in C# 6.0 with .NET 4.5 (Mono)
    var positives = A.Where(x => x > 0).Distinct().OrderBy(x => x).ToArray();
    if(positives.Count() == 0) return 1;
    int prev = 0;
    for(int i =0; i < positives.Count(); i++){

        if(positives[i] != prev + 1){
            return prev + 1;
        }
         prev = positives[i];
    }
    return positives.Last() + 1;
}

How to make JQuery-AJAX request synchronous

I added dataType as json and made the response as json:

PHP

echo json_encode(array('success'=>$res)); //send the response as json **use this instead of echo $res in your php file**

JavaScript

  var ajaxSubmit = function(formE1) {

        var password = $.trim($('#employee_password').val());    
        $.ajax({
            type: "POST",
            async: "false",
            url: "checkpass.php",
            data: "password="+password,
            dataType:'json',  //added this so the response is in json
            success: function(result) {
                var arr=result.success;
                if(arr == "Successful")
                {    return true;
                }
                else
                {    return false;
                }
            }
        });

  return false
}

How to set up a cron job to run an executable every hour?

The solution to solve this is to find out why you're getting the segmentation fault, and fix that.

Why do we always prefer using parameters in SQL statements?

Other answers cover why parameters are important, but there is a downside! In .net, there are several methods for creating parameters (Add, AddWithValue), but they all require you to worry, needlessly, about the parameter name, and they all reduce the readability of the SQL in the code. Right when you're trying to meditate on the SQL, you need to hunt around above or below to see what value has been used in the parameter.

I humbly claim my little SqlBuilder class is the most elegant way to write parameterized queries. Your code will look like this...

C#

var bldr = new SqlBuilder( myCommand );
bldr.Append("SELECT * FROM CUSTOMERS WHERE ID = ").Value(myId);
//or
bldr.Append("SELECT * FROM CUSTOMERS WHERE NAME LIKE ").FuzzyValue(myName);
myCommand.CommandText = bldr.ToString();

Your code will be shorter and much more readable. You don't even need extra lines, and, when you're reading back, you don't need to hunt around for the value of parameters. The class you need is here...

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

public class SqlBuilder
{
private StringBuilder _rq;
private SqlCommand _cmd;
private int _seq;
public SqlBuilder(SqlCommand cmd)
{
    _rq = new StringBuilder();
    _cmd = cmd;
    _seq = 0;
}
public SqlBuilder Append(String str)
{
    _rq.Append(str);
    return this;
}
public SqlBuilder Value(Object value)
{
    string paramName = "@SqlBuilderParam" + _seq++;
    _rq.Append(paramName);
    _cmd.Parameters.AddWithValue(paramName, value);
    return this;
}
public SqlBuilder FuzzyValue(Object value)
{
    string paramName = "@SqlBuilderParam" + _seq++;
    _rq.Append("'%' + " + paramName + " + '%'");
    _cmd.Parameters.AddWithValue(paramName, value);
    return this;
}
public override string ToString()
{
    return _rq.ToString();
}
}

How to call a button click event from another method

Add it to the instance of the Click delegate:

ChildNode.Click += SubGraphButton_Click

which is inkeeping with the pattern .NET events follow (Observer).

Setting the filter to an OpenFileDialog to allow the typical image formats?

Complete solution in C# is here:

private void btnSelectImage_Click(object sender, RoutedEventArgs e)
{
    // Configure open file dialog box 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
    dlg.Filter = "";

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
    string sep = string.Empty;

    foreach (var c in codecs)
    {
       string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim();
       dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, codecName, c.FilenameExtension);
       sep = "|";
    }

    dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, "All Files", "*.*"); 

    dlg.DefaultExt = ".png"; // Default file extension 

    // Show open file dialog box 
    Nullable<bool> result = dlg.ShowDialog();

    // Process open file dialog box results 
    if (result == true)
    {
       // Open document 
       string fileName  = dlg.FileName;
       // Do something with fileName  
    }
} 

Insert, on duplicate update in PostgreSQL?

With PostgreSQL 9.1 this can be achieved using a writeable CTE (common table expression):

WITH new_values (id, field1, field2) as (
  values 
     (1, 'A', 'X'),
     (2, 'B', 'Y'),
     (3, 'C', 'Z')

),
upsert as
( 
    update mytable m 
        set field1 = nv.field1,
            field2 = nv.field2
    FROM new_values nv
    WHERE m.id = nv.id
    RETURNING m.*
)
INSERT INTO mytable (id, field1, field2)
SELECT id, field1, field2
FROM new_values
WHERE NOT EXISTS (SELECT 1 
                  FROM upsert up 
                  WHERE up.id = new_values.id)

See these blog entries:


Note that this solution does not prevent a unique key violation but it is not vulnerable to lost updates.
See the follow up by Craig Ringer on dba.stackexchange.com

JavaScript: Get image dimensions

Get image size with jQuery

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

Get image size with JavaScript

function getMeta(url){   
    var img = new Image();
    img.onload = function(){
        alert( this.width+' '+ this.height );
    };
    img.src = url;
}

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

How to expand/collapse a diff sections in Vimdiff?

Actually if you do Ctrl+W W, you won't need to add that extra Ctrl. Does the same thing.

Difference between hamiltonian path and euler path

An Euler path is a path that uses every edge of a graph exactly once.and it must have exactly two odd vertices.the path starts and ends at different vertex. A Hamiltonian cycle is a cycle that contains every vertex of the graph hence you may not use all the edges of the graph.

Python circular importing?

I was using the following:

from module import Foo

foo_instance = Foo()

but to get rid of circular reference I did the following and it worked:

import module.foo

foo_instance = foo.Foo()

Write / add data in JSON file using Node.js

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
    
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

Java String declaration

String str = new String("SOME")

always create a new object on the heap

String str="SOME" 

uses the String pool

Try this small example:

        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "hello";

        System.err.println(s1 == s2);
        System.err.println(s2 == s3);

To avoid creating unnecesary objects on the heap use the second form.

How to disable HTML links

In Razor (.cshtml) you can do:

@{
    var isDisabled = true;
}

<a href="@(isDisabled ? "#" : @Url.Action("Index", "Home"))" @(isDisabled ? "disabled=disabled" : "") class="btn btn-default btn-lg btn-block">Home</a>

Filter Linq EXCEPT on properties

MoreLinq has something useful for this MoreLinq.Source.MoreEnumerable.ExceptBy

https://github.com/gsscoder/morelinq/blob/master/MoreLinq/ExceptBy.cs

namespace MoreLinq
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    static partial class MoreEnumerable
    {
        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector)
        {
            return ExceptBy(first, second, keySelector, null);
        }

        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <param name="keyComparer">The equality comparer to use to determine whether or not keys are equal.
        /// If null, the default equality comparer for <c>TSource</c> is used.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            if (first == null) throw new ArgumentNullException("first");
            if (second == null) throw new ArgumentNullException("second");
            if (keySelector == null) throw new ArgumentNullException("keySelector");
            return ExceptByImpl(first, second, keySelector, keyComparer);
        }

        private static IEnumerable<TSource> ExceptByImpl<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            var keys = new HashSet<TKey>(second.Select(keySelector), keyComparer);
            foreach (var element in first)
            {
                var key = keySelector(element);
                if (keys.Contains(key))
                {
                    continue;
                }
                yield return element;
                keys.Add(key);
            }
        }
    }
}

-XX:MaxPermSize with or without -XX:PermSize

By playing with parameters as -XX:PermSize and -Xms you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.

A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).

WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms equal to -Xmx or -XX:PermSize equal to -XX:MaxPermSize as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.

As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)

Laravel 5.4 create model, controller and migration in single artisan command

How I was doing it until now:

php artisan make:model Customer
php artisan make:controller CustomersController --resource

Apparently, there’s a quicker way:

php artisan make:controller CustomersController --model=Customer

C# binary literals

string sTable="static class BinaryTable\r\n{";
string stemp = "";
for (int i = 0; i < 256; i++)
{
stemp = System.Convert.ToString(i, 2);
while(stemp.Length<8) stemp = "0" + stemp;
sTable += "\tconst char nb" + stemp + "=" + i.ToString() + ";\r\n";
}
sTable += "}";
Clipboard.Clear();
Clipboard.SetText ( sTable);
MessageBox.Show(sTable);

Using this, for 8bit binary, I use this to make a static class and it puts it into the clipboard.. Then it gets pasted into the project and added to the Using section, so anything with nb001010 is taken out of a table, at least static, but still... I use C# for a lot of PIC graphics coding and use 0b101010 a lot in Hi-Tech C

--sample from code outpt--

static class BinaryTable
{   const char nb00000000=0;
    const char nb00000001=1;
    const char nb00000010=2;
    const char nb00000011=3;
    const char nb00000100=4;
//etc, etc, etc, etc, etc, etc, etc, 
}

:-) NEAL

Optimum way to compare strings in JavaScript?

You can use the comparison operators to compare strings. A strcmp function could be defined like this:

function strcmp(a, b) {
    if (a.toString() < b.toString()) return -1;
    if (a.toString() > b.toString()) return 1;
    return 0;
}

Edit    Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:

function strcmp(a, b) {
    a = a.toString(), b = b.toString();
    for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
    if (i === n) return 0;
    return a.charAt(i) > b.charAt(i) ? -1 : 1;
}

MVC3 DropDownListFor - a simple example?

You should do like this:

@Html.DropDownListFor(m => m.ContribType, 
                new SelectList(Model.ContribTypeOptions, 
                               "ContribId", "Value"))

Where:

m => m.ContribType

is a property where the result value will be.

Getting the textarea value of a ckeditor textarea with javascript

You could integrate a function on JQuery

jQuery.fn.CKEditorValFor = function( element_id ){
  return CKEDITOR.instances[element_id].getData();
}

and passing as a parameter the ckeditor element id

var campaign_title_value = $().CKEditorValFor('CampaignTitle');

How do I create ColorStateList programmatically?

Bouncing off the answer by Jonathan Ellis, in Kotlin you can define a helper function to make the code a bit more idiomatic and easier to read, so you can write this instead:

val colorList = colorStateListOf(
    intArrayOf(-android.R.attr.state_enabled) to Color.BLACK,
    intArrayOf(android.R.attr.state_enabled) to Color.RED,
)

colorStateListOf can be implemented like this:

fun colorStateListOf(vararg mapping: Pair<IntArray, Int>): ColorStateList {
    val (states, colors) = mapping.unzip()
    return ColorStateList(states.toTypedArray(), colors.toIntArray())
}

I also have:

fun colorStateListOf(@ColorInt color: Int): ColorStateList {
    return ColorStateList.valueOf(color)
}

So that I can call the same function name, no matter if it's a selector or single color.

How to set lifetime of session

The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.

For set the time life in php, you can use the function session_set_cookie_params, before the session_start:

session_set_cookie_params(3600,"/");
session_start();

For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.

But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.

You can have a Table "Sessions":

  • session_id int
  • session_hash varchar(20)
  • session_data text

And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:

On login:

setcookie('sessid', $sessionid, 604800);      // One week or seven days
setcookie('sesshash', $sessionhash, 604800);  // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function

If the user return:

if (isset($_COOKIE['sessid'])) {
    if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
        $_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
    } else {
        // Dont validate the hash, possible session falsification
    }
}

Obviously, save all session/cookies calls, before sending data.

How to indent HTML tags in Notepad++

I have a solution for you.

Just you need to install a plugin named Indent By Fold.

You can install this by going through Plugins -> Plugin Manager -> Show Plugin Manager. OR Plugins -> Plugins Admin -> chekmark Indent By Fold from list than install

Then just select the list item and all you need is to type the first word then you got it.

you can use this plugin from a plugin in the menu bar.


Why are the Level.FINE logging messages not showing?

Loggers only log the message, i.e. they create the log records (or logging requests). They do not publish the messages to the destinations, which is taken care of by the Handlers. Setting the level of a logger, only causes it to create log records matching that level or higher.

You might be using a ConsoleHandler (I couldn't infer where your output is System.err or a file, but I would assume that it is the former), which defaults to publishing log records of the level Level.INFO. You will have to configure this handler, to publish log records of level Level.FINER and higher, for the desired outcome.

I would recommend reading the Java Logging Overview guide, in order to understand the underlying design. The guide covers the difference between the concept of a Logger and a Handler.

Editing the handler level

1. Using the Configuration file

The java.util.logging properties file (by default, this is the logging.properties file in JRE_HOME/lib) can be modified to change the default level of the ConsoleHandler:

java.util.logging.ConsoleHandler.level = FINER

2. Creating handlers at runtime

This is not recommended, for it would result in overriding the global configuration. Using this throughout your code base will result in a possibly unmanageable logger configuration.

Handler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.FINER);
Logger.getAnonymousLogger().addHandler(consoleHandler);

Dropdown select with images

PLAIN JAVASCRIPT:

DEMO: http://codepen.io/tazotodua/pen/orhdp

_x000D_
_x000D_
var shownnn = "yes";_x000D_
var dropd = document.getElementById("image-dropdown");_x000D_
_x000D_
function showww() {_x000D_
  dropd.style.height = "auto";_x000D_
  dropd.style.overflow = "y-scroll";_x000D_
}_x000D_
_x000D_
function hideee() {_x000D_
    dropd.style.height = "30px";_x000D_
    dropd.style.overflow = "hidden";_x000D_
  }_x000D_
  //dropd.addEventListener('mouseover', showOrHide, false);_x000D_
  //dropd.addEventListener('click',showOrHide , false);_x000D_
_x000D_
_x000D_
function myfuunc(imgParent) {_x000D_
  hideee();_x000D_
  var mainDIVV = document.getElementById("image-dropdown");_x000D_
  imgParent.parentNode.removeChild(imgParent);_x000D_
  mainDIVV.insertBefore(imgParent, mainDIVV.childNodes[0]);_x000D_
}
_x000D_
#image-dropdown {_x000D_
  display: inline-block;_x000D_
  border: 1px solid;_x000D_
}_x000D_
#image-dropdown {_x000D_
  height: 30px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
/*#image-dropdown:hover {} */_x000D_
_x000D_
#image-dropdown .img_holder {_x000D_
  cursor: pointer;_x000D_
}_x000D_
#image-dropdown img.flagimgs {_x000D_
  height: 30px;_x000D_
}_x000D_
#image-dropdown span.iTEXT {_x000D_
  position: relative;_x000D_
  top: -8px;_x000D_
}
_x000D_
<!-- not tested in mobiles -->_x000D_
_x000D_
_x000D_
<div id="image-dropdown" onmouseleave="hideee();">_x000D_
  <div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
    <img class="flagimgs first" src="http://www.google.com/tv/images/socialyoutube.png" /> <span class="iTEXT">First</span>_x000D_
  </div>_x000D_
  <div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
    <img class="flagimgs second" src="http://www.google.com/cloudprint/learn/images/icons/fiabee.png" /> <span class="iTEXT">Second</span>_x000D_
  </div>_x000D_
  <div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
    <img class="flagimgs second" src="http://www.google.com/tv/images/lplay.png" /> <span class="iTEXT">Third</span>_x000D_
  </div>_x000D_
  <div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
    <img class="flagimgs second" src="http://www.google.com/cloudprint/learn/images/icons/cloudprintlite.png" /> <span class="iTEXT">Fourth</span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What can I use for good quality code coverage for C#/.NET?

C# Test Coverage Tool has very low overhead, handles huge systems of files, intuitive GUI showing coverage on specific files, and generated report with coverage breakdown at method, class, and package levels.

Cast Int to enum in Java

MyEnum.values()[x] is an expensive operation. If the performance is a concern, you may want to do something like this:

public enum MyEnum {
    EnumValue1,
    EnumValue2;

    public static MyEnum fromInteger(int x) {
        switch(x) {
        case 0:
            return EnumValue1;
        case 1:
            return EnumValue2;
        }
        return null;
    }
}

What are the advantages of Sublime Text over Notepad++ and vice-versa?

Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.

Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.

Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.

Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?

What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.

PHP function to build query string from array

Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

In my case I copied a ssl config from another machine and had the wrong IP in <VirtualHost wrong.ip.addr.here:443>. Changed IP to what it should be, restarted httpd and the site loaded over SSL as expected.

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

If you put Datetime nullable like DateTime? in your model it doesn't throw exception.

I solved the problem like this in my case.

Import SQL file by command line in Windows 7

If those commands don't seems to work -- I assure you they do --, check the top of your sql dump file for the use of :

CREATE DATABASE {mydbname}

and

USE {mydbname}

The last parameter {mydbname} of the mysql command can be misleading : if CREATE DATABASE an USE are in your dump file, the import will in fact be done in this database, not in the one in the mysql command.

The mysqldump command that will prompt CREATE DATABASE and USE is :

mysqldump.exe -h localhost -u root --databases xxx > xxx.sql

Use mysqldump without --databases to leave out CREATE DATABASE and USE :

mysqldump.exe -h localhost -u root xxx > xxx.sql

How to get Git to clone into current directory

In addition to @StephaneDelcroix's answer, before using:

git clone [email protected]/my-project.git .

make sure that your current dir is empty by using

ls -a

how to assign a block of html code to a javascript variable

I recommend to use mustache templating frame work. https://github.com/janl/mustache.js/.

<body>
       ....................
       <!--Put your html variable in a script and set the type to "x-tmpl-mustache"-->
       <script id="template" type="x-tmpl-mustache">
           <div class='saved' >
           <div >test.test</div> <div class='remove'>[Remove]</div></div>
    </script>
</body>

  //You can use it without jquery.
  var template = $('#template').html();
  var rendered = Mustache.render(template);
  $('#target').html(rendered);

Why I recommend this?

Soon or latter you will try to replace some part of the HTML variable and make it dynamic. Dealing with this as an HTML String will be a headache. Here is where Mustache magic can help you.

<script id="template" type="x-tmpl-mustache">
 <div class='remove'>  {{ name }}! </div> ....
</script>

and

 var template = $('#template').html();
 // You can pass dynamic template values
  var rendered = Mustache.render(template, {name: "Luke"});
  $('#target').html(rendered);

There are lot more features.

How do I monitor all incoming http requests?

What you need to do is configure Fiddler to work as a "reverse proxy"

There are instructions on 2 different ways you can do this on Fiddler's website. Here is a copy of the steps:


Step #0

Before either of the following options will work, you must enable other computers to connect to Fiddler. To do so, click Tools > Fiddler Options > Connections and tick the "Allow remote computers to connect" checkbox. Then close Fiddler.

Option #1: Configure Fiddler as a Reverse-Proxy

Fiddler can be configured so that any traffic sent to http://127.0.0.1:8888 is automatically sent to a different port on the same machine. To set this configuration:

  1. Start REGEDIT
  2. Create a new DWORD named ReverseProxyForPort inside HKCU\SOFTWARE\Microsoft\Fiddler2.
  3. Set the DWORD to the local port you'd like to re-route inbound traffic to (generally port 80 for a standard HTTP server)
  4. Restart Fiddler
  5. Navigate your browser to http://127.0.0.1:8888

Option #2: Write a FiddlerScript rule

Alternatively, you can write a rule that does the same thing.

Say you're running a website on port 80 of a machine named WEBSERVER. You're connecting to the website using Internet Explorer Mobile Edition on a Windows SmartPhone device for which you cannot configure the web proxy. You want to capture the traffic from the phone and the server's response.

  1. Start Fiddler on the WEBSERVER machine, running on the default port of 8888.
  2. Click Tools | Fiddler Options, and ensure the "Allow remote clients to connect" checkbox is checked. Restart if needed.
  3. Choose Rules | Customize Rules.
  4. Inside the OnBeforeRequest handler, add a new line of code:
    if (oSession.host.toLowerCase() == "webserver:8888") oSession.host = "webserver:80";
  5. On the SmartPhone, navigate to http://webserver:8888

Requests from the SmartPhone will appear in Fiddler. The requests are forwarded from port 8888 to port 80 where the webserver is running. The responses are sent back through Fiddler to the SmartPhone, which has no idea that the content originally came from port 80.

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

In my case the asp.net application can usually connect to database without any problems. I noticed such message in logs. I turn on the SQL server logs and I find out this message:

2016-10-28 10:27:10.86 Logon       Login failed for user '****'. Reason: Failed to open the explicitly specified database '****'. [CLIENT: <local machine>]
2016-10-28 10:27:13.22 Server      SQL Server is terminating because of a system shutdown. This is an informational message only. No user action is required.

So it seems that server was restarting and that SQL server whad been shutting down a bit earlier then ASP.NET application and the database was not available for few seconds before server restart.

Resize font-size according to div size

The answer that i am presenting is very simple, instead of using "px","em" or "%", i'll use "vw". In short it might look like this:- h1 {font-size: 5.9vw;} when used for heading purposes.

See this:Demo

For more details:Main tutorial

What to do with commit made in a detached head

You can just do git merge <commit-number> or git cherry-pick <commit> <commit> ...

As suggested by Ryan Stewart you may also create a branch from the current HEAD:

git branch brand-name

Or just a tag:

git tag tag-name

Get local IP address

For a laugh, thought I'd try and get a single LINQ statement by using the new C# 6 null-conditional operator. Looks pretty crazy and probably horribly inefficient, but it works.

private string GetLocalIPv4(NetworkInterfaceType type = NetworkInterfaceType.Ethernet)
{
    // Bastardized from: http://stackoverflow.com/a/28621250/2685650.

    return NetworkInterface
        .GetAllNetworkInterfaces()
        .FirstOrDefault(ni =>
            ni.NetworkInterfaceType == type
            && ni.OperationalStatus == OperationalStatus.Up
            && ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null
            && ni.GetIPProperties().UnicastAddresses.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork) != null
        )
        ?.GetIPProperties()
        .UnicastAddresses
        .FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork)
        ?.Address
        ?.ToString()
        ?? string.Empty;
}

Logic courtesy of Gerardo H (and by reference compman2408).

Java, how to compare Strings with String Arrays

Iterate over the codes array using a loop, asking for each of the elements if it's equals() to usercode. If one element is equal, you can stop and handle that case. If none of the elements is equal to usercode, then do the appropriate to handle that case. In pseudocode:

found = false
foreach element in array:
  if element.equals(usercode):
    found = true
    break

if found:
  print "I found it!"
else:
  print "I didn't find it"

Filter values only if not null using lambda in Java8

In this particular example I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable the Optional stuff is really for return types not to be doing logic... but really neither here nor there.

I wanted to point out that java.util.Objects has a nice method for this in a broad case, so you can do this:

cars.stream()
    .filter(Objects::nonNull)

Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:

cars.stream()
    .filter(car -> Objects.nonNull(car))

To partially answer the question at hand to return the list of car names that starts with "M":

cars.stream()
    .filter(car -> Objects.nonNull(car))
    .map(car -> car.getName())
    .filter(carName -> Objects.nonNull(carName))
    .filter(carName -> carName.startsWith("M"))
    .collect(Collectors.toList());

Once you get used to the shorthand lambdas you could also do this:

cars.stream()
    .filter(Objects::nonNull)
    .map(Car::getName)        // Assume the class name for car is Car
    .filter(Objects::nonNull)
    .filter(carName -> carName.startsWith("M"))
    .collect(Collectors.toList());

Unfortunately once you .map(Car::getName) you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:

cars.stream()
    .filter(car -> Objects.nonNull(car))
    .filter(car -> Objects.nonNull(car.getName()))
    .filter(car -> car.getName().startsWith("M"))
    .collect(Collectors.toList());

Google Android USB Driver and ADB

  1. modify android_winusb.inf
  2. Sign the driver
  3. modify adb

I also instaled generic adb driver from http://adbdriver.com/ and it works.

SQL update from one Table to another based on a ID match

Oracle 11g

merge into Sales_Import
using RetrieveAccountNumber
on (Sales_Import.LeadId = RetrieveAccountNumber.LeadId)
when matched then update set Sales_Import.AccountNumber = RetrieveAccountNumber.AccountNumber;

What is an Intent in Android?

In a broad view, we can define Intent as

When one Activity wants to start another activity it creates an Object called Intent that specifies which Activity it wants to start.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

1) in a query window in SQL Server Management Studio, run the command:

SET SHOWPLAN_ALL ON

2) run your slow query

3) your query will not run, but the execution plan will be returned. store this output

4) run your fast version of the query

5) your query will not run, but the execution plan will be returned. store this output

6) compare the slow query version output to the fast query version output.

7) if you still don't know why one is slower, post both outputs in your question (edit it) and someone here can help from there.

Java: Instanceof and Generics

I had the same problem and here is my solution (very humble, @george: this time compiling AND working ...).

My probem was inside an abstract class that implements Observer. The Observable fires method update(...) with Object class that can be any kind of Object.

I only want to handler Objects of type T

The solution is to pass the class to the constructor in order to be able to compare types at runtime.

public abstract class AbstractOne<T> implements Observer {

  private Class<T> tClass;
    public AbstractOne(Class<T> clazz) {
    tClass = clazz;
  }

  @Override
  public void update(Observable o, Object arg) {
    if (tClass.isInstance(arg)) {
      // Here I am, arg has the type T
      foo((T) arg);
    }
  }

  public abstract foo(T t);

}

For the implementation we just have to pass the Class to the constructor

public class OneImpl extends AbstractOne<Rule> {
  public OneImpl() {
    super(Rule.class);
  }

  @Override
  public void foo(Rule t){
  }
}

Iterating over ResultSet and adding its value in an ArrayList

Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet to List, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator:

jOOQ 3.8 or less

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(r -> Arrays.stream(r.intoArray()))
   .collect(Collectors.toList());

jOOQ 3.9

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(Record::intoStream)
   .collect(Collectors.toList());

(Disclaimer, I work for the company behind jOOQ)

relative path in require_once doesn't work

In my case it doesn't work, even with __DIR__ or getcwd() it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:

if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/

I have MAMP with php 5.4.10 and my folder hierarchy is basilar:

q.php 
w.php 
e.php 
r.php 
cache/a.php 
cache/b.php 
setting/a.php 
setting/b.php

....

Using BigDecimal to work with currencies

Or, wait for JSR-354. Java Money and Currency API coming soon!

Change Circle color of radio button

I made it short way like this (Working on API pre 21 as well as post 21)

Your radio button in xml should look like this

  <RadioButton android:id="@+id/radioid"                    
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"                 
                android:button="@drawable/radiodraw" />

in radiodraw.xml

  <?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">    
      <item android:state_checked="false" >
          <shape  android:shape="oval" >
              <stroke android:width="1dp" android:color="#000"/>
              <size android:width="30dp" android:height="30dp"/>
              <solid android:color="@android:color/transparent"/>
          </shape>
      </item>
      <item android:state_checked="true">
          <layer-list>
              <item>
                  <shape android:shape="oval">
                      <stroke android:width="1dp" android:color="#000"/>
                      <size android:width="30dp" android:height="30dp"/>
                      <solid android:color="@android:color/transparent"/>
                  </shape>
              </item>
              <item android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp">
                  <shape android:shape="oval">
                      <solid android:width="1dp" android:color="#000"/>
                      <size android:width="10dp" android:height="10dp"/>
                  </shape>
              </item>
          </layer-list>
      </item>
  </selector>

have to add color transparent for drawing the unchecked status ;else it draw solid black oval.

Regular Expression to select everything before and up to a particular text

This matches everything up to ".txt" (without including it):

^.*(?=(\.txt))

How to list physical disks?

Might want to include the old A: and B: drives as you never know who might be using them! I got tired of USB drives bumping my two SDHC drives that are just for Readyboost. I had been assigning them to High letters Z: Y: with a utility that will assign drive letters to devices as you wish. I wondered.... Can I make a Readyboost drive letter A: ? YES! Can I put my second SDHC drive letter as B: ? YES!

I've used Floppy Drives back in the day, never thought that A: or B: would come in handy for Readyboost.

My point is, don't assume A: & B: will not be used by anyone for anything You might even find the old SUBST command being used!

Python 3.4.0 with MySQL database

mysqlclient is a fork of MySQLdb and can serve as a drop-in replacement with Python 3.4 support. If you have trouble building it on Windows, you can download it from Christoph Gohlke's Unofficial Windows Binaries for Python Extension Packages

Accessing certain pixel RGB value in openCV

The low-level way would be to access the matrix data directly. In an RGB image (which I believe OpenCV typically stores as BGR), and assuming your cv::Mat variable is called frame, you could get the blue value at location (x, y) (from the top left) this way:

frame.data[frame.channels()*(frame.cols*y + x)];

Likewise, to get B, G, and R:

uchar b = frame.data[frame.channels()*(frame.cols*y + x) + 0];    
uchar g = frame.data[frame.channels()*(frame.cols*y + x) + 1];
uchar r = frame.data[frame.channels()*(frame.cols*y + x) + 2];

Note that this code assumes the stride is equal to the width of the image.

Best way to show a loading/progress indicator?

Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".

Currently the recommended method is to use a DialogFragment :

public class MySpinnerDialog extends DialogFragment {

    public MySpinnerDialog() {
        // use empty constructors. If something is needed use onCreate's
    }

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {

        _dialog = new ProgressDialog(getActivity());
        this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
        _dialog.setMessage("Spinning.."); // set your messages if not inflated from XML

        _dialog.setCancelable(false);  

        return _dialog;
    }
}

Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:

FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");

Once your server has responded complete you will dismiss it:

myInstance.dismiss()

Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide

How to add an element to the beginning of an OrderedDict?

I would suggest adding a prepend() method to this pure Python ActiveState recipe or deriving a subclass from it. The code to do so could be a fairly efficient given that the underlying data structure for ordering is a linked-list.

Update

To prove this approach is feasible, below is code that does what's suggested. As a bonus, I also made a few additional minor changes to get to work in both Python 2.7.15 and 3.7.1.

A prepend() method has been added to the class in the recipe and has been implemented in terms of another method that's been added named move_to_end(), which was added to OrderedDict in Python 3.2.

prepend() can also be implemented directly, almost exactly as shown at the beginning of @Ashwini Chaudhary's answer—and doing so would likely result in it being slightly faster, but that's been left as an exercise for the motivated reader...

# Ordered Dictionary for Py2.4 from https://code.activestate.com/recipes/576693

# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
# Passes Python2.7's test suite and incorporates all the latest updates.

try:
    from thread import get_ident as _get_ident
except ImportError:  # Python 3
#    from dummy_thread import get_ident as _get_ident
    from _thread import get_ident as _get_ident  # Changed - martineau

try:
    from _abcoll import KeysView, ValuesView, ItemsView
except ImportError:
    pass

class MyOrderedDict(dict):
    'Dictionary that remembers insertion order'
    # An inherited dict maps keys to values.
    # The inherited dict provides __getitem__, __len__, __contains__, and get.
    # The remaining methods are order-aware.
    # Big-O running times for all methods are the same as for regular dictionaries.

    # The internal self.__map dictionary maps keys to links in a doubly linked list.
    # The circular doubly linked list starts and ends with a sentinel element.
    # The sentinel element never gets deleted (this simplifies the algorithm).
    # Each link is stored as a list of length three:  [PREV, NEXT, KEY].

    def __init__(self, *args, **kwds):
        '''Initialize an ordered dictionary.  Signature is the same as for
        regular dictionaries, but keyword arguments are not recommended
        because their insertion order is arbitrary.

        '''
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        try:
            self.__root
        except AttributeError:
            self.__root = root = []  # sentinel node
            root[:] = [root, root, None]
            self.__map = {}
        self.__update(*args, **kwds)

    def prepend(self, key, value):  # Added to recipe.
        self.update({key: value})
        self.move_to_end(key, last=False)

    #### Derived from cpython 3.2 source code.
    def move_to_end(self, key, last=True):  # Added to recipe.
        '''Move an existing element to the end (or beginning if last==False).

        Raises KeyError if the element does not exist.
        When last=True, acts like a fast version of self[key]=self.pop(key).
        '''
        PREV, NEXT, KEY = 0, 1, 2

        link = self.__map[key]
        link_prev = link[PREV]
        link_next = link[NEXT]
        link_prev[NEXT] = link_next
        link_next[PREV] = link_prev
        root = self.__root

        if last:
            last = root[PREV]
            link[PREV] = last
            link[NEXT] = root
            last[NEXT] = root[PREV] = link
        else:
            first = root[NEXT]
            link[PREV] = root
            link[NEXT] = first
            root[NEXT] = first[PREV] = link
    ####

    def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
        'od.__setitem__(i, y) <==> od[i]=y'
        # Setting a new item creates a new link which goes at the end of the linked
        # list, and the inherited dictionary is updated with the new key/value pair.
        if key not in self:
            root = self.__root
            last = root[0]
            last[1] = root[0] = self.__map[key] = [last, root, key]
        dict_setitem(self, key, value)

    def __delitem__(self, key, dict_delitem=dict.__delitem__):
        'od.__delitem__(y) <==> del od[y]'
        # Deleting an existing item uses self.__map to find the link which is
        # then removed by updating the links in the predecessor and successor nodes.
        dict_delitem(self, key)
        link_prev, link_next, key = self.__map.pop(key)
        link_prev[1] = link_next
        link_next[0] = link_prev

    def __iter__(self):
        'od.__iter__() <==> iter(od)'
        root = self.__root
        curr = root[1]
        while curr is not root:
            yield curr[2]
            curr = curr[1]

    def __reversed__(self):
        'od.__reversed__() <==> reversed(od)'
        root = self.__root
        curr = root[0]
        while curr is not root:
            yield curr[2]
            curr = curr[0]

    def clear(self):
        'od.clear() -> None.  Remove all items from od.'
        try:
            for node in self.__map.itervalues():
                del node[:]
            root = self.__root
            root[:] = [root, root, None]
            self.__map.clear()
        except AttributeError:
            pass
        dict.clear(self)

    def popitem(self, last=True):
        '''od.popitem() -> (k, v), return and remove a (key, value) pair.
        Pairs are returned in LIFO order if last is true or FIFO order if false.

        '''
        if not self:
            raise KeyError('dictionary is empty')
        root = self.__root
        if last:
            link = root[0]
            link_prev = link[0]
            link_prev[1] = root
            root[0] = link_prev
        else:
            link = root[1]
            link_next = link[1]
            root[1] = link_next
            link_next[0] = root
        key = link[2]
        del self.__map[key]
        value = dict.pop(self, key)
        return key, value

    # -- the following methods do not depend on the internal structure --

    def keys(self):
        'od.keys() -> list of keys in od'
        return list(self)

    def values(self):
        'od.values() -> list of values in od'
        return [self[key] for key in self]

    def items(self):
        'od.items() -> list of (key, value) pairs in od'
        return [(key, self[key]) for key in self]

    def iterkeys(self):
        'od.iterkeys() -> an iterator over the keys in od'
        return iter(self)

    def itervalues(self):
        'od.itervalues -> an iterator over the values in od'
        for k in self:
            yield self[k]

    def iteritems(self):
        'od.iteritems -> an iterator over the (key, value) items in od'
        for k in self:
            yield (k, self[k])

    def update(*args, **kwds):
        '''od.update(E, **F) -> None.  Update od from dict/iterable E and F.

        If E is a dict instance, does:           for k in E: od[k] = E[k]
        If E has a .keys() method, does:         for k in E.keys(): od[k] = E[k]
        Or if E is an iterable of items, does:   for k, v in E: od[k] = v
        In either case, this is followed by:     for k, v in F.items(): od[k] = v

        '''
        if len(args) > 2:
            raise TypeError('update() takes at most 2 positional '
                            'arguments (%d given)' % (len(args),))
        elif not args:
            raise TypeError('update() takes at least 1 argument (0 given)')
        self = args[0]
        # Make progressively weaker assumptions about "other"
        other = ()
        if len(args) == 2:
            other = args[1]
        if isinstance(other, dict):
            for key in other:
                self[key] = other[key]
        elif hasattr(other, 'keys'):
            for key in other.keys():
                self[key] = other[key]
        else:
            for key, value in other:
                self[key] = value
        for key, value in kwds.items():
            self[key] = value

    __update = update  # let subclasses override update without breaking __init__

    __marker = object()

    def pop(self, key, default=__marker):
        '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised.

        '''
        if key in self:
            result = self[key]
            del self[key]
            return result
        if default is self.__marker:
            raise KeyError(key)
        return default

    def setdefault(self, key, default=None):
        'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
        if key in self:
            return self[key]
        self[key] = default
        return default

    def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key]

    def __reduce__(self):
        'Return state information for pickling'
        items = [[k, self[k]] for k in self]
        inst_dict = vars(self).copy()
        for k in vars(MyOrderedDict()):
            inst_dict.pop(k, None)
        if inst_dict:
            return (self.__class__, (items,), inst_dict)
        return self.__class__, (items,)

    def copy(self):
        'od.copy() -> a shallow copy of od'
        return self.__class__(self)

    @classmethod
    def fromkeys(cls, iterable, value=None):
        '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
        and values equal to v (which defaults to None).

        '''
        d = cls()
        for key in iterable:
            d[key] = value
        return d

    def __eq__(self, other):
        '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
        while comparison to a regular mapping is order-insensitive.

        '''
        if isinstance(other, MyOrderedDict):
            return len(self)==len(other) and self.items() == other.items()
        return dict.__eq__(self, other)

    def __ne__(self, other):
        return not self == other

    # -- the following methods are only used in Python 2.7 --

    def viewkeys(self):
        "od.viewkeys() -> a set-like object providing a view on od's keys"
        return KeysView(self)

    def viewvalues(self):
        "od.viewvalues() -> an object providing a view on od's values"
        return ValuesView(self)

    def viewitems(self):
        "od.viewitems() -> a set-like object providing a view on od's items"
        return ItemsView(self)

if __name__ == '__main__':

    d1 = MyOrderedDict([('a', '1'), ('b', '2')])
    d1.update({'c':'3'})
    print(d1)  # -> MyOrderedDict([('a', '1'), ('b', '2'), ('c', '3')])

    d2 = MyOrderedDict([('a', '1'), ('b', '2')])
    d2.prepend('c', 100)
    print(d2)  # -> MyOrderedDict([('c', 100), ('a', '1'), ('b', '2')])

Recursively look for files with a specific extension

Without using find:

du -a $directory | awk '{print $2}' | grep '\.in$'

(How) can I count the items in an enum?

Add a entry, at the end of your enum, called Folders_MAX or something similar and use this value when initializing your arrays.

ContainerClass* m_containers[Folders_MAX];

Html table tr inside td

Full Example:

_x000D_
_x000D_
<table border="1" style="width:100%;">
  <tr>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
  </tr>
  <tr>
    <td>Item 1</td>
    <td>Item 1</td>
    <td>
      <table border="1" style="width: 100%;">
        <tr>
          <td>Name 1</td>
          <td>Price 1</td>
        </tr>
        <tr>
          <td>Name 2</td>
          <td>Price 2</td>
        </tr>
        <tr>
          <td>Name 3</td>
          <td>Price 3</td>
        </tr>
      </table>
    </td>
    <td>Item 1</td>
  </tr>
  <tr>
    <td>Item 2</td>
    <td>Item 2</td>
    <td>Item 2</td>
    <td>Item 2</td>
  </tr>
  <tr>
    <td>Item 3</td>
    <td>Item 3</td>
    <td>Item 3</td>
    <td>Item 3</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

  1. Login to your Gmail account using the web browser.

  2. Click on this link to enable applications to access your account: https://accounts.google.com/b/0/DisplayUnlockCaptcha

  3. Click on Continue button to complete the step.

  4. Now try again to send the email from your PHP script. It should work.

In R, how to find the standard error of the mean?

A version of John's answer above that removes the pesky NA's:

stderr <- function(x, na.rm=FALSE) {
  if (na.rm) x <- na.omit(x)
  sqrt(var(x)/length(x))
}

Android ImageView's onClickListener does not work

The same thing is happening for me.

The reason is: I have used a list view with margin Top so the data is starting from the bottom of the image, but the actual list view is overlapping on the image which is not visible. So even if we click on the image, the action is not performed. To fix this, I have made the list view start from the below the image so that it is not overlapping on the image itself.

Connecting to remote URL which requires authentication using Java

As i have came here looking for an Android-Java-Answer i am going to do a short summary:

  1. Use java.net.Authenticator as shown by James van Huis
  2. Use Apache Commons HTTP Client, as in this Answer
  3. Use basic java.net.URLConnection and set the Authentication-Header manually like shown here

If you want to use java.net.URLConnection with Basic Authentication in Android try this code:

URL url = new URL("http://www.mywebsite.com/resource");
URLConnection urlConnection = url.openConnection();
String header = "Basic " + new String(android.util.Base64.encode("user:pass".getBytes(), android.util.Base64.NO_WRAP));
urlConnection.addRequestProperty("Authorization", header);
// go on setting more request headers, reading the response, etc

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

Load image with jQuery and append it to the DOM

I imagine that you define your image something like this:

<img id="image_portrait" src="" alt="chef etat"  width="120" height="135"  />

You can simply load/update image for this tag and chage/set atts (width,height):

var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);

Log4net does not write the log in the log file

In my case I had to give the IIS_IUSRS Read\write permission to the log file.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

How to wrap text in LaTeX tables?

If you want to wrap your text but maintain alignment then you can wrap that cell in a minipage or varwidth environment (varwidth comes from the varwidth package). Varwidth will be "as wide as it's contents but no wider than X". You can create a custom column type which acts like "p{xx}" but shrinks to fit by using

\newcolumntype{M}[1]{>{\begin{varwidth}[t]{#1}}l<{\end{varwidth}}}

which may require the array package. Then when you use something like \begin{tabular}{llM{2in}} the first two columns we be normal left-aligned and the third column will be normal left aligned but if it gets wider than 2in then the text will be wrapped.

Windows command to convert Unix line endings?

Here's a simple unix2dos.bat file that preserves blank lines and exclamation points:

@echo off
setlocal DisableDelayedExpansion
for /f "tokens=1,* delims=:" %%k in ('findstr /n "^" %1') do echo.%%l

The output goes to standard out, so redirect unix2dos.bat output to a file if so desired.

It avoids the pitfalls of other previously proposed for /f batch loop solutions by:
1) Working with delayed expansion off, to avoid eating up exclamation marks.
2) Using the for /f tokenizer itself to remove the line number from the findstr /n output lines.
(Using findstr /n is necessary to also get blank lines: They would be dropped if for /f read directly from the input file.)

But, as Jeb pointed out in a comment below, the above solution has one drawback the others don't: It drops colons at the beginning of lines.

So 2020-04-06 update just for fun, here's another 1-liner based on findstr.exe, that seems to work fine without the above drawbacks:

@echo off
setlocal DisableDelayedExpansion
for /f "tokens=* delims=0123456789" %%l in ('findstr /n "^" %1') do echo%%l

The additional tricks are:
3) Use digits 0-9 as delimiters, so that tokens=* skips the initial line number.
4) Use the colon, inserted by findstr /n after the line number, as the token separator after the echo command.

I'll leave it to Jeb to explain if there are corner cases where echo:something might fail :-)
All I can say is that this last version successfully restored line endings on my huge batch library, so exceptions, if any, must be quite rare!

SQL Server 2008: TOP 10 and distinct together

This is the right answer and you can find 3 heights value from table

SELECT TOP(1)  T.id FROM (SELECT DISTINCT TOP(3) st.id  FROM Table1 AS t1 , Table2 AS t2 WHERE t1.id=t2.id ORDER BY (t2.id) DESC ) T ORDER BY(T.id) ASC

Converting a string to a date in DB2

In format function your can use timestamp_format function. Example, if the format is YYYYMMDD you can do it :

select TIMESTAMP_FORMAT(yourcolumnchar, 'YYYYMMDD') as YouTimeStamp 
from yourtable

you can then adapt then format with elements format foundable here

What is the default access specifier in Java?

First of all let me say one thing there is no such term as "Access specifier" in java. We should call everything as "Modifiers". As we know that final, static, synchronised, volatile.... are called as modifiers, even Public, private, protected, default, abstract should also be called as modifiers . Default is such a modifiers where physical existence is not there but no modifiers is placed then it should be treated as default modifiers.

To justify this take one example:

public class Simple{  
    public static void main(String args[]){  
     System.out.println("Hello Java");  
    }  
}  

Output will be: Hello Java

Now change public to private and see what compiler error you get: It says "Modifier private is not allowed here" What conclusion is someone can be wrong or some tutorial can be wrong but compiler cannot be wrong. So we can say there is no term access specifier in java everything is modifiers.

how do I get a new line, after using float:left?

Another approach that's a little more semantic is to have a UL defined as your total 6 image width, each LI defined as float left and width defined - so that when LI #7 hits, it runs into the boundry of the UL, and is pushed down to the new row. You'll still have an open float that you'll want to clear after the /UL - but that can be done on the next element of the page, or as a clear div. Here's sort of the idea, you may have to mess with actual values, but this should give you the idea. The code is a little cleaner.

 <style type="text/css"> 
ul#imageSet { width: 600px; margin: 0; padding:0; }
ul#imageSet li { float: left; width: 100px;  height: 188px; margin: 0; padding:0; position: relative; list-style-type: none; }
.cornerimage { position: absolute; bottom: 0; right: 0; } 
h3.nextelement { clear: both; }
</style>


<ul id="imageSet">
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
     <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
</ul>


<h3 class="nextelement">Next Element in Doc</h3>

Inversion of Control vs Dependency Injection

enter image description here
source

IoC (Inversion of Control) :- It’s a generic term and implemented in several ways (events, delegates etc).

DI (Dependency Injection) :- DI is a sub-type of IoC and is implemented by constructor injection, setter injection or Interface injection.

But, Spring supports only the following two types :

  • Setter Injection
    • Setter-based DI is realized by calling setter methods on the user’s beans after invoking a no-argument constructor or no-argument static factory method to instantiate their bean.
  • Constructor Injection
    • Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.Using this we can validate that the injected beans are not null and fail fast(fail on compile time and not on run-time), so while starting application itself we get NullPointerException: bean does not exist. Constructor injection is Best practice to inject dependencies.

Why is there no String.Empty in Java?

Apache StringUtils addresses this problem too.

Failings of the other options:

  • isEmpty() - not null safe. If the string is null, throws an NPE
  • length() == 0 - again not null safe. Also does not take into account whitespace strings.
  • Comparison to EMPTY constant - May not be null safe. Whitespace problem

Granted StringUtils is another library to drag around, but it works very well and saves loads of time and hassle checking for nulls or gracefully handling NPEs.

"implements Runnable" vs "extends Thread" in Java

This maybe isn't an answer but anyway; there is one more way to create threads:

Thread t = new Thread() {
    public void run() {
        // Code here
    }
}

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

How to save a Python interactive session?

There is %history magic for printing and saving the input history (and optionally the output).

To store your current session to a file named my_history.py:

>>> %hist -f my_history.py

History IPython stores both the commands you enter, and the results it produces. You can easily go through previous commands with the up- and down-arrow keys, or access your history in more sophisticated ways.

You can use the %history magic function to examine past input and output. Input history from previous sessions is saved in a database, and IPython can be configured to save output history.

Several other magic functions can use your input history, including %edit, %rerun, %recall, %macro, %save and %pastebin. You can use a standard format to refer to lines:

%pastebin 3 18-20 ~1/1-5

This will take line 3 and lines 18 to 20 from the current session, and lines 1-5 from the previous session.

See %history? for the Docstring and more examples.

Also, be sure to explore the capabilities of %store magic for lightweight persistence of variables in IPython.

Stores variables, aliases and macros in IPython’s database.

d = {'a': 1, 'b': 2}
%store d  # stores the variable
del d

%store -r d  # Refresh the variable from IPython's database.
>>> d
{'a': 1, 'b': 2}

To autorestore stored variables on startup, specifyc.StoreMagic.autorestore = True in ipython_config.py.

Android - how do I investigate an ANR?

my issue with ANR , after much work i found out that a thread was calling a resource that did not exist in the layout, instead of returning an exception , i got ANR ...

MySQL > Table doesn't exist. But it does (or it should)

For me on Mac OS (MySQL DMG Installation) a simple restart of the MySQL server solved the problem. I am guessing the hibernation caused it.

Getting Raw XML From SOAPMessage in Java

this works

 final StringWriter sw = new StringWriter();

try {
    TransformerFactory.newInstance().newTransformer().transform(
        new DOMSource(soapResponse.getSOAPPart()),
        new StreamResult(sw));
} catch (TransformerException e) {
    throw new RuntimeException(e);
}
System.out.println(sw.toString());
return sw.toString();