Programs & Examples On #Scratch memory

Capturing a single image from my webcam in Java or Python

It can be done by using ecapture First, run

pip install ecapture

Then in a new python script type:

    from ecapture import ecapture as ec

    ec.capture(0,"test","img.jpg")

More information from thislink

Where can I download Eclipse Android bundle?

You don't actually need the bundle as the ADT can be used with just any latest Eclipse IDE.


1. Make sure you have JDK installed.

  1. Download latest eclipse.

  2. Download latest ADT plugin ADT-XX.X.X.zip. As of this answer the current version is ADT-23.0.7.zip (More versions at http://developer.android.com/tools/sdk/eclipse-adt.html)

  3. Open Eclipse and follow the following steps:

    • Open Help > Install New Software > Add > Archive
    • Navigate to where you downloaded your ADT plugin and select it.
    • Check Developer Tools, click Next, accept any licenses and Finish
  4. After restarting Eclipse, if you are not able to open a layout file go to step 4 but instead of selecting archive add https://dl-ssl.google.com/android/eclipse/ in the Location: textbox. Press Ok, update the ADT and restart Eclipse. Close and reopen the layout files and you'll be good to go.

  5. Run the Android SDK Manager to update its components.


EDIT: The ADT plugin has long since been deprecated. For more information visit this link:

https://developer.android.com/studio/tools/sdk/eclipse-adt.html

SQL: how to select a single id ("row") that meets multiple criteria from a single column

SELECT DISTINCT (user_id) 
FROM [user]
WHERE user.user_id In (select user_id from user where ancestry = 'England') 
    And user.user_id In (select user_id from user where ancestry = 'France') 
    And user.user_id In (select user_id from user where ancestry = 'Germany');`

check the null terminating character in char*

Your '/0' should be '\0' .. you got the slash reversed/leaning the wrong way. Your while should look like:

while (*(forward++)!='\0') 

though the != '\0' part of your expression is optional here since the loop will continue as long as it evaluates to non-zero (null is considered zero and will terminate the loop).

All "special" characters (i.e., escape sequences for non-printable characters) use a backward slash, such as tab '\t', or newline '\n', and the same for null '\0' so it's easy to remember.

Using BeautifulSoup to search HTML for string

The following line is looking for the exact NavigableString 'Python':

>>> soup.body.findAll(text='Python')
[]

Note that the following NavigableString is found:

>>> soup.body.findAll(text='Python Jobs') 
[u'Python Jobs']

Note this behaviour:

>>> import re
>>> soup.body.findAll(text=re.compile('^Python$'))
[]

So your regexp is looking for an occurrence of 'Python' not the exact match to the NavigableString 'Python'.

Loop through each row of a range in Excel

Dim a As Range, b As Range

Set a = Selection

For Each b In a.Rows
    MsgBox b.Address
Next

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

Changing the JFrame title

newTitle is a local variable where you create the fields. So when that functions ends, the variable newTitle, does not exist anymore. (The JTextField that was referenced by newTitle does still exist however.)

Thus, increase the scope of the variable, so that you can access it another method.

public SomeFrame extends JFrame {
   JTextField myTitle;//can be used anywhere in this class

   creationOfTheFields()
   {
   //other code
      myTitle = new JTextField("spam");  
      myTitle.setBounds(80, 40, 225, 20);
      options.add(myTitle);
   //blabla other code
   }

   private void New_Name()  
   {  
      this.setTitle(myTitle.getText());  
   } 
}

How to horizontally align ul to center of div?

ul {
      text-align: center;
      list-style: inside;
    }

How do you compare two version Strings in Java?

public int CompareVersions(String version1, String version2)
{
    String[] string1Vals = version1.split("\\.");
    String[] string2Vals = version2.split("\\.");

    int length = Math.max(string1Vals.length, string2Vals.length);

    for (int i = 0; i < length; i++)
    {
        Integer v1 = (i < string1Vals.length)?Integer.parseInt(string1Vals[i]):0;
        Integer v2 = (i < string2Vals.length)?Integer.parseInt(string2Vals[i]):0;

        //Making sure Version1 bigger than version2
        if (v1 > v2)
        {
            return 1;
        }
        //Making sure Version1 smaller than version2
        else if(v1 < v2)
        {
            return -1;
        }
    }

    //Both are equal
    return 0;
}

How to mock static methods in c# using MOQ framework?

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

Hope that helps.

Get a list of distinct values in List

mcilist = (from mci in mcilist select mci).Distinct().ToList();

Top 5 time-consuming SQL queries in Oracle

While searching I got the following query which does the job with one assumption(query execution time >6 seconds)


SELECT username, sql_text, sofar, totalwork, units

FROM v$sql,v$session_longops

WHERE sql_address = address AND sql_hash_value = hash_value

ORDER BY address, hash_value, child_number;


I think above query will list the details for current user.

Comments are welcome!!

SQL Query to find the last day of the month

In Snowflake (and likely other SQL engines), you can use LAST_DAY.

select to_date('2015-05-08T23:39:20.123-07:00') as "DATE",
       last_day("DATE", 'MONTH') as "LAST DAY OF MONTH";

Which returns:

DATE         LAST DAY OF MONTH
2015-05-08          2015-05-31

go to link on button click - jquery

$('.button1').click(function() {
   window.location = "www.example.com/index.php?id=" + this.id;
});

First of all using window.location is better as according to specification document.location value was read-only and might cause you headaches in older/different browsers. Check notes @MDC DOM document.location page

And for the second - using attr jQuery method to get id is a bad practice - you should use direct native DOM accessor this.id as the value assigned to this is normal DOM element.

Turn off textarea resizing

As per the question, i have listed the answers in javascript

By Selecting TagName

document.getElementsByTagName('textarea')[0].style.resize = "none";

By Selecting Id

document.getElementById('textArea').style.resize = "none";

Getting Class type from String

Not sure what you are asking, but... Class.forname, maybe?

How to call an async method from a getter or setter?

When I ran into this problem, trying to run an async method synchronicity from either a setter or a constructor got me into a deadlock on the UI thread, and using an event handler required too many changes in the general design.
The solution was, as often is, to just write explicitly what I wanted to happen implicitly, which was to have another thread handle the operation and to get the main thread to wait for it to finish:

string someValue=null;
var t = new Thread(() =>someValue = SomeAsyncMethod().Result);
t.Start();
t.Join();

You could argue that I abuse the framework, but it works.

Automated Python to Java translation

Yes Jython does this, but it may or may not be what you want

How do you check if a selector matches something in jQuery?

Alternatively:

if( jQuery('#elem').get(0) ) {}

why are there two different kinds of for loops in java?

Something none of the other answers touch on is that your first loop is indexing though the list. Whereas the for-each loop is using an Iterator. Some lists like LinkedList will iterate faster with an Iterator versus get(i). This is because because link list's iterator keeps track of the current pointer. Whereas each get in your for i=0 to 9 has to recompute the offset into the linked list. In general, its better to use for-each or an Iterator because it will be using Collections iterator, which in theory is optimized for the collection type.

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Basically, you get connections in the Sleep state when :

  • a PHP script connects to MySQL
  • some queries are executed
  • then, the PHP script does some stuff that takes time
    • without disconnecting from the DB
  • and, finally, the PHP script ends
    • which means it disconnects from the MySQL server

So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.

A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.


Another thing, that I often see when there is some load on the server :

  • There are more and more requests coming to Apache
    • which means many pages to generate
  • Each PHP script, in order to generate a page, connects to the DB and does some queries
  • These queries take more and more time, as the load on the DB server increases
  • Which means more processes keep stacking up

A solution that can help is to reduce the time your queries take -- optimizing the longest ones.

'innerText' works in IE, but not in Firefox

innerText has been added to Firefox and should be available in the FF45 release: https://bugzilla.mozilla.org/show_bug.cgi?id=264412

A draft spec has been written and is expected to be incorporated into the HTML living standard in the future: http://rocallahan.github.io/innerText-spec/, https://github.com/whatwg/html/issues/465

Note that currently the Firefox, Chrome and IE implementations are all incompatible. Going forward, we can probably expect Firefox, Chrome and Edge to converge while old IE remains incompatible.

See also: https://github.com/whatwg/compat/issues/5

Programmatically change the src of an img tag

if you use the JQuery library use this instruction:

$("#imageID").attr('src', 'srcImage.jpg');

Static Classes In Java

Outer classes cannot be static, but nested/inner classes can be. That basically helps you to use the nested/inner class without creating an instance of the outer class.

git remote add with other SSH port

Best answer doesn't work for me. I needed ssh:// from the beggining.

# does not work
git remote set-url origin [email protected]:10000/aaa/bbbb/ccc.git
# work
git remote set-url origin ssh://[email protected]:10000/aaa/bbbb/ccc.git

The import com.google.android.gms cannot be resolved

In my case or all using android studio

you can import google play service

place in your build.gradle

compile 'com.google.android.gms:play-services:7.8.0'

or latest version of play services depend in time you watch this answer

More Specific import

please review this individual gradle imports

https://developers.google.com/android/guides/setup

Google Maps

com.google.android.gms:play-services-maps:7.8.0

error may occurred

if you face error while you sync project with gradle files

enter image description here

make sure you install latest update

1- Android Support Repository.

2- Android Support Library.

3- Google Repository.

4-Google Play Services.

enter image description here

You may need restart your android studio to response

How do I convert datetime.timedelta to minutes, hours in Python?

There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. timedelta object supports str() operation that will do this. It works even in Python 2.6.

>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'

How to change the sender's name or e-mail address in mutt?

100% Working!

To send HTML contents in the body of the mail on the go with Sender and Recipient mail address in single line, you may try the below,

export EMAIL="[email protected]" && mutt -e "my_hdr Content-Type: text/html" -s "Test Mail" "[email protected]" < body_html.html

File: body_html.html

<HTML>
<HEAD> Test Mail </HEAD>
<BODY>
<p>This is a <strong><span style="color: #ff0000;">test mail!</span></strong></p>
</BODY>
</HTML>

Note: Tested in RHEL, CentOS, Ubuntu.

Angularjs simple file download causes router to redirect

If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.

I hope it, will be helpfull.

HTML :

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

DIRECTIVE :

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

IN CONTROLLER:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

IN SERVICE:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

BACKEND(on SPRING):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}

Unable to run Java code with Intellij IDEA

I had the similar issue and solved it by doing the below step.

  1. Go to "Run" menu and "Edit configuration"
  2. Click on add(+) icon and select Application from the list.
  3. In configuration name your Main class: name of your main class.
  4. Working Directory : It should point till the src folder of your project. C:\Users\name\Work\ProjectName\src

    This is where I had issue and after correcting this, I could see the run option for that class.

OPTION (RECOMPILE) is Always Faster; Why?

Necroing this question but there's an explanation that no-one seems to have considered.

STATISTICS - Statistics are not available or misleading

If all of the following are true:

  1. The columns feedid and feedDate are likely to be highly correlated (e.g. a feed id is more specific than a feed date and the date parameter is redundant information).
  2. There is no index with both columns as sequential columns.
  3. There are no manually created statistics covering both these columns.

Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.

How to set time to midnight for current day?

Related, so I thought I would post for others. If you want to find the UTC of the start of today (for your timezone) the following code works for any UTC offset (-23.5 thru +23.5). This looks like we add X hours then subtract X hours, but the important thing is the ".Date" after the add.

double utcOffset= 10.0;  // Set to your UTC offset in hours (eg. Melbourne Australia)
var now = DateTime.UtcNow;

var startOfToday = now.AddHours(utcOffset - 24.0).Date;
startOfToday = startOfToday.AddHours(24.0 - utcOffset);

Ignore case in Python strings

This is how you'd do it with re:

import re
p = re.compile('^hello$', re.I)
p.match('Hello')
p.match('hello')
p.match('HELLO')

In C# check that filename is *possibly* valid (not that it exists)

I've had luck using regular expressions as others have shown.

One thing to keep in mind is that Windows at least prohibits some filenames that otherwise containlegal characters. A few come to mind: com, nul, prn.

I don't have it with me now, but I have a regex that takes these filename into consideration. If you want I can post it, otherwise I'm sure you can find it the same way I did: Google.

-Jay

Simplest Way to Test ODBC on WIndows

You can use the "Test Connection" feature after creating the ODBC connection through Control Panel > Administrative Tools > Data Sources.

To test a SQL command itself you could try:

http://www.sqledit.com/odbc/runner.html

http://www.sqledit.com/sqlrun.zip

Or (perhaps easier and more useful in the long run) you can make a test ASP.NET or PHP page in a couple minutes to run SQL statement yourself through IIS.

Adb over wireless without usb cable at all for not rooted phones

Had same issue, however I'm using Macbook Pro (2016) which has USB-c only and I forgot my adapter at home.

Since unable to run adb at all on my development machine, I found a different approach.

Connecting phone with USB cable to another computer (in same WiFi) and enable run adb tcpip from there.

Master-machine : computer where development goes on, with only USB-C connectors

Slave-machine: another computer with USB and in same WiFi

Steps:

  1. Connect the phone to a different computer (slave-machine)
  2. Run adb usb && adb tcpip 5555 from there
  3. On master machine

    deko$: adb devices
    List of devices attached
    
    deko$: adb connect 10.0.20.153:5555
    connected to 10.0.20.153:5555
    
  4. Now Android Studio or Xamarin can install and run app on the phone


Sidenote:

I also tested Bluetooth tethering from the Phone to Master-machine and successfully connected to phone. Both Android Studio and Xamarin worked well, however the upload process, from Xamarin was taking long time. But it works.

Python Requests throwing SSLError

If you don't bother about certificate just use verify=False.

import requests

url = "Write your url here"

returnResponse = requests.get(url, verify=False)

Android emulator: How to monitor network traffic?

I would suggest you use Wireshark.

Steps:

  1. Install Wireshark.
  2. Select the network connection that you are using for the calls(for eg, select the Wifi if you are using it)
  3. There will be many requests and responses, close extra applications.
  4. Usually the requests are in green color, once you spot your request, copy the destination address and use the filter on top by typing ip.dst==52.187.182.185 by putting the destination address.

You can make use of other filtering techniques mentioned here to get specific traffic.

Why is a div with "display: table-cell;" not affected by margin?

You can use inner divs to set the margin.

<div style="display: table-cell;">
   <div style="margin:5px;background-color: red;">1</div>
</div>
<div style="display: table-cell; ">
  <div style="margin:5px;background-color: green;">1</div>
</div>

JS Fiddle

Material Design not styling alert dialogs

You can consider this project: https://github.com/fengdai/AlertDialogPro

It can provide you material theme alert dialogs almost the same as lollipop's. Compatible with Android 2.1.

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

How to call a stored procedure from Java and JPA

Try this code:

return em.createNativeQuery("{call getEmployeeDetails(?,?)}",
                               EmployeeDetails.class)           
                               .setParameter(1, employeeId)
                               .setParameter(2, companyId).getResultList();

Passing a dictionary to a function as keyword parameters

Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

So my example becomes:

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

Update using LINQ to SQL

 DataClassesDataContext dc = new DataClassesDataContext();

 FamilyDetail fd = dc.FamilyDetails.Single(p => p.UserId == 1);

 fd.FatherName=txtFatherName.Text;
        fd.FatherMobile=txtMobile.Text;
        fd.FatherOccupation=txtFatherOccu.Text;
        fd.MotherName=txtMotherName.Text;
        fd.MotherOccupation=txtMotherOccu.Text;
        fd.Phone=txtPhoneNo.Text;
        fd.Address=txtAddress.Text;
        fd.GuardianName=txtGardianName.Text;

        dc.SubmitChanges();

Declaring and initializing a string array in VB.NET

Array initializer support for type inference were changed in Visual Basic 10 vs Visual Basic 9.

In previous version of VB it was required to put empty parens to signify an array. Also, it would define the array as object array unless otherwise was stated:

' Integer array
Dim i as Integer() = {1, 2, 3, 4} 

' Object array
Dim o() = {1, 2, 3} 

Check more info:

Visual Basic 2010 Breaking Changes

Collection and Array Initializers in Visual Basic 2010

Change status bar color with AppCompat ActionBarActivity

I'm not sure I understand the problem.

I you want to change the status bar color programmatically (and provided the device has Android 5.0) then you can use Window.setStatusBarColor(). It shouldn't make a difference whether the activity is derived from Activity or ActionBarActivity.

Just try doing:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.setStatusBarColor(Color.BLUE);
}

Just tested this with ActionBarActivity and it works alright.


Note: Setting the FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag programmatically is not necessary if your values-v21 styles file has it set already, via:

    <item name="android:windowDrawsSystemBarBackgrounds">true</item>

What's the difference between a POST and a PUT HTTP REQUEST?

Please see: http://zacharyvoase.com/2009/07/03/http-post-put-diff/

I’ve been getting pretty annoyed lately by a popular misconception by web developers that a POST is used to create a resource, and a PUT is used to update/change one.

If you take a look at page 55 of RFC 2616 (“Hypertext Transfer Protocol – HTTP/1.1”), Section 9.6 (“PUT”), you’ll see what PUT is actually for:

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

There’s also a handy paragraph to explain the difference between POST and PUT:

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request – the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource.

It doesn’t mention anything about the difference between updating/creating, because that’s not what it’s about. It’s about the difference between this:

obj.set_attribute(value) # A POST request.

And this:

obj.attribute = value # A PUT request.

So please, stop the spread of this popular misconception. Read your RFCs.

Observable.of is not a function

RxJS 6

When upgrading to version 6 of the RxJS library and not using the rxjs-compat package the following code

import 'rxjs/add/observable/of';   
  // ...
  return Observable.of(res);

has to be changed into

import { of } from 'rxjs';
  // ...
  return of(res);

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

Android Closing Activity Programmatically

you can use finishAffinity(); to close all the activity..

On npm install: Unhandled rejection Error: EACCES: permission denied

Simply do sudo npm cache clean --force --unsafe-perm and npm i will go normally.

C++ trying to swap values in a vector

after passing the vector by reference

swap(vector[position],vector[otherPosition]);

will produce the expected result.

Which rows are returned when using LIMIT with OFFSET in MySQL?

You will get output from column value 9 to 26 as you have mentioned OFFSET as 8

How to get current value of RxJS Subject or Observable?

I encountered the same problem in child components where initially it would have to have the current value of the Subject, then subscribe to the Subject to listen to changes. I just maintain the current value in the Service so it is available for components to access, e.g. :

import {Storage} from './storage';
import {Injectable} from 'angular2/core';
import {Subject}    from 'rxjs/Subject';

@Injectable()
export class SessionStorage extends Storage {

  isLoggedIn: boolean;

  private _isLoggedInSource = new Subject<boolean>();
  isLoggedIn = this._isLoggedInSource.asObservable();
  constructor() {
    super('session');
    this.currIsLoggedIn = false;
  }
  setIsLoggedIn(value: boolean) {
    this.setItem('_isLoggedIn', value, () => {
      this._isLoggedInSource.next(value);
    });
    this.isLoggedIn = value;
  }
}

A component that needs the current value could just then access it from the service, i.e,:

sessionStorage.isLoggedIn

Not sure if this is the right practice :)

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

How do I set log4j level on the command line?

In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):

-Droot.log.level=TRACE

Java ArrayList replace at specific index

Use the set() method: see doc

arraylist.set(index,newvalue);

Encoding Error in Panda read_csv

This works in Mac as well you can use

df= pd.read_csv('Region_count.csv', encoding ='latin1')

how to use "AND", "OR" for RewriteCond on Apache?

This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.

In the top section you'll quickly spot the defines used to name these flags:

#define CONDFLAG_NONE               1<<0
#define CONDFLAG_NOCASE             1<<1
#define CONDFLAG_NOTMATCH           1<<2
#define CONDFLAG_ORNEXT             1<<3
#define CONDFLAG_NOVARY             1<<4

and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:

else if (   strcasecmp(key, "ornext") == 0
         || strcasecmp(key, "OR") == 0    ) {
    cfg->flags |= CONDFLAG_ORNEXT;
}

The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):

# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
    rewritecond_entry *c = &conds[i];

    # execute the current Condition, see if it matches
    rc = apply_rewrite_cond(c, ctx);

    # does this Condition have an 'OR' flag?
    if (c->flags & CONDFLAG_ORNEXT) {
        if (!rc) {
            /* One condition is false, but another can be still true. */
            continue;
        }
        else {
            /* skip the rest of the chained OR conditions */
            while (   i < rewriteconds->nelts
                   && c->flags & CONDFLAG_ORNEXT) {
                c = &conds[++i];
            }
        }
    }
    else if (!rc) {
        return 0;
    }
}

You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) ). If you would, for example, have these Conditions:

RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D

it would be interpreted as if ( (A OR B OR C) and D ).

How to center an image horizontally and align it to the bottom of the container?

wouldn't

margin-left:auto;
margin-right:auto;

added to the .image_block a img do the trick?
Note that that won't work in IE6 (maybe 7 not sure)
there you will have to do on .image_block the container Div

text-align:center;

position:relative; could be a problem too.

What should I do if the current ASP.NET session is null?

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:

If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.

Edit

In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.

AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.

If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.

Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.

Is there a command to undo git init?

I'm running Windows 7 with git bash console. The above commands wouldn't work for me.

So I did it via Windows Explorer. I checked show hidden files, went to my projects directory and manually deleted the .git folder. Then back in the command line I checked by running git status.

Which returned...

fatal: Not a git repository (or any of the parent directories): .git

Which is exactly the result I wanted. It returned that the directory is not a git repository (anymore!).

Tomcat: LifecycleException when deploying

Might be super trivial but worth a check prior to waste some time.

At my case the mysql service was down.

When you have a java app including JPA / Hibernate it is checking the database connection on startup. Just found out by looking into the looks where it had an entity manager error.

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

C#: Looping through lines of multiline string

from MSDN for StringReader

    string textReaderText = "TextReader is the abstract base " +
        "class of StreamReader and StringReader, which read " +
        "characters from streams and strings, respectively.\n\n" +

        "Create an instance of TextReader to open a text file " +
        "for reading a specified range of characters, or to " +
        "create a reader based on an existing stream.\n\n" +

        "You can also use an instance of TextReader to read " +
        "text from a custom backing store using the same " +
        "APIs you would use for a string or a stream.\n\n";

    Console.WriteLine("Original text:\n\n{0}", textReaderText);

    // From textReaderText, create a continuous paragraph 
    // with two spaces between each sentence.
    string aLine, aParagraph = null;
    StringReader strReader = new StringReader(textReaderText);
    while(true)
    {
        aLine = strReader.ReadLine();
        if(aLine != null)
        {
            aParagraph = aParagraph + aLine + " ";
        }
        else
        {
            aParagraph = aParagraph + "\n";
            break;
        }
    }
    Console.WriteLine("Modified text:\n\n{0}", aParagraph);

Multidimensional arrays in Swift

As stated by the other answers, you are adding the same array of rows to each column. To create a multidimensional array you must use a loop

var NumColumns = 27
var NumRows = 52
var array = Array<Array<Double>>()
for column in 0..NumColumns {
    array.append(Array(count:NumRows, repeatedValue:Double()))
}

SQL "between" not inclusive

your code

SELECT * FROM Cases WHERE created_at BETWEEN '2013-05-01' AND '2013-05-01'

how SQL reading it

SELECT * FROM Cases WHERE '2013-05-01 22:25:19' BETWEEN '2013-05-01 00:00:00' AND '2013-05-01 00:00:00'

if you don't mention time while comparing DateTime and Date by default hours:minutes:seconds will be zero in your case dates are the same but if you compare time created_at is 22 hours ahead from your end date range

if the above is clear you fix this in many ways like putting ending hours in your end date eg BETWEEN '2013-05-01' AND ''2013-05-01 23:59:59''

OR

simply cast create_at as date like cast(created_at as date) after casting as date '2013-05-01 22:25:19' will be equal to '2013-05-01 00:00:00'

Difference between Visual Basic 6.0 and VBA

Do you want compare VBA with VB-Classic (VB6..) or VB.NET?

VBA (Visual Basic for Applications) is a vb-classic-based script language embedded in Microsoft Office applications. I think it's language features are similar to those of VB5 (it just lacks some few builtin functions), but:

You have access to the office document you wrote the VBA-script for and so you can e.g.

  • Write macros (=automated routines for little recurring tasks in your office-work)
  • Define new functions for excel-cell-formula
  • Process office data

Example: Set the value of an excel-cell

ActiveSheet.Cells("A1").Value = "Foo"

VBC and -.NET are no script languages. You use them to write standalone-applications with separate IDE's which you can't do with VBA (VBA-scripts just "exist" in Office)

VBA has nothing to do with VB.NET (they just have a similar syntax).

AngularJS/javascript converting a date String to date object

_x000D_
_x000D_
//JS_x000D_
//First Solution_x000D_
moment(myDate)_x000D_
_x000D_
//Second Solution_x000D_
moment(myDate).format('YYYY-MM-DD HH:mm:ss')_x000D_
//or_x000D_
moment(myDate).format('YYYY-MM-DD')_x000D_
_x000D_
//Third Solution_x000D_
myDate = $filter('date')(myDate, "dd/MM/yyyy");
_x000D_
<!--HTML-->_x000D_
<!-- First Solution -->_x000D_
{{myDate  | date:'M/d/yyyy HH:mm:ss'}}_x000D_
<!-- or -->_x000D_
{{myDate  | date:'medium'}}_x000D_
_x000D_
<!-- Second Solution -->_x000D_
{{myDate}}_x000D_
_x000D_
<!-- Third Solution -->_x000D_
{{myDate}}
_x000D_
_x000D_
_x000D_

Put icon inside input element in a form

 <label for="fileEdit">
    <i class="fa fa-cloud-upload">
    </i>
    <input id="fileEdit" class="hidden" type="file" name="addImg" ng-file-change="onImageChange( $files )" ng-multiple="false" accept="{{ contentType }}"/>
  </label>

For example you can use this : label with hidden input (icon is present).

Access parent DataContext from DataTemplate

Yes, you can solve it using the ElementName=Something as suggested by Juve.

BUT!

If a child element (on which you use this kind of binding) is a user control which uses the same element name as you specify in the parent control, then the binding goes to the wrong object!!

I know this post is not a solution but I thought everyone who uses the ElementName in the binding should know this, since it's a possible runtime bug.

<UserControl x:Class="MyNiceControl"
             x:Name="TheSameName">
   the content ...
</UserControl>

<UserControl x:Class="AnotherUserControl">
        <ListView x:Name="TheSameName">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <MyNiceControl Width="{Binding DataContext.Width, ElementName=TheSameName}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</UserControl>

What's the right way to pass form element state to sibling/parent elements?

I'm surprised that there are no answers with a straightforward idiomatic React solution at the moment I'm writing. So here's the one (compare the size and complexity to others):

class P extends React.Component {
    state = { foo : "" };

    render(){
        const { foo } = this.state;

        return (
            <div>
                <C1 value={ foo } onChange={ x => this.setState({ foo : x })} />
                <C2 value={ foo } />
            </div>
        )
    }
}

const C1 = ({ value, onChange }) => (
    <input type="text"
           value={ value }
           onChange={ e => onChange( e.target.value ) } />
);

const C2 = ({ value }) => (
    <div>Reacting on value change: { value }</div>
);

I'm setting the state of a parent element from a child element. This seems to betray the design principle of React: single-direction data flow.

Any controlled input (idiomatic way of working with forms in React) updates the parent state in its onChange callback and still doesn't betray anything.

Look carefully at C1 component, for instance. Do you see any significant difference in the way how C1 and built-in input component handle the state changes? You should not, because there is none. Lifting up the state and passing down value/onChange pairs is idiomatic for raw React. Not usage of refs, as some answers suggest.

Android file chooser

I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:

My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.

private void startCreation(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_PICK);
    Uri startDir = Uri.fromFile(new File("/sdcard"));

    intent.setDataAndType(startDir,
            "vnd.android.cursor.dir/lysesoft.andexplorer.file");
    intent.putExtra("browser_filter_extension_whitelist", "*.csv");
    intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
    intent.putExtra("browser_title_background_color",
            getText(R.string.browser_title_background_color));
    intent.putExtra("browser_title_foreground_color",
            getText(R.string.browser_title_foreground_color));
    intent.putExtra("browser_list_background_color",
            getText(R.string.browser_list_background_color));
    intent.putExtra("browser_list_fontscale", "120%");
    intent.putExtra("browser_list_layout", "2");

    try{
         ApplicationInfo info = getPackageManager()
                                 .getApplicationInfo("lysesoft.andexplorer", 0 );

            startActivityForResult(intent, PICK_REQUEST_CODE);
    } catch( PackageManager.NameNotFoundException e ){
        showInstallResultMessage(R.string.error_install_andexplorer);
    } catch (Exception e) {
        Log.w(TAG, e.getMessage());
    }
}

This methos is just pick up a dialog and if user wants install the external application from market

private void showInstallResultMessage(int msg_id) {
    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setMessage(getText(msg_id));
    dialog.setButton(getText(R.string.button_ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    dialog.setButton2(getText(R.string.button_install),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
                    startActivity(intent);
                    finish();
                }
            });
    dialog.show();
}

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

You need MouseClick instead of Click event handler, reference.

switch (e.Button) {

    case MouseButtons.Left:
    // Left click
    break;

    case MouseButtons.Right:
    // Right click
    break;
    ...
}

Convert AM/PM time to 24 hours format?

using System;

class Solution
{
    static string timeConversion(string s)
    {
        return DateTime.Parse(s).ToString("HH:mm");
    }

    static void Main(string[] args)
    {
        Console.WriteLine(timeConversion("01:00 PM"));
        Console.Read();
    }
}

Is there any way to prevent input type="number" getting negative values?

Here's an angular 2 solution:

create a class OnlyNumber

import {Directive, ElementRef, HostListener} from '@angular/core';

@Directive({
  selector: '[OnlyNumber]'
})
export class OnlyNumber {

  // Allow decimal numbers. The \. is only allowed once to occur
  private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);

  // Allow key codes for special events. Reflect :
  // Backspace, tab, end, home
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];

  constructor(private el: ElementRef) {
  }

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }

    // Do not use event.keycode this is deprecated.
    // See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
    let current: string = this.el.nativeElement.value;
    // We need this because the current value on the DOM element
    // is not yet updated with the value from this event
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

add OnlyNumber to declarations in app.module.ts and use like it like this anywhere in your app

<input OnlyNumber="true">

How to clone git repository with specific revision/changeset?

TL;DR - Just create a tag in the source repository against the commit you want to clone up to and use the tag in the fetch command. You can delete the tag from the original repo later to clean up.

Well, its 2014 and it looks like Charles Bailey's accepted answer from 2010 is well and truly outdated by now and most (all?) of the other answers involve cloning, which many people are hoping to avoid.

The following solution achieves what the OP and many others are looking for, which is a way to create a copy of a repository, including history, but only up to a certain commit.

Here are the commands I used with git version 2.1.2 to clone a local repo (ie. a repository in another directory) up to a certain point:

# in the source repository, create a tag against the commit you want to check out
git tag -m "Temporary tag" tmptag <sha1>

# create a new directory and change into that directory
cd somewhere_else;mkdir newdir;cd newdir

# ...and create a new repository
git init

# add the source repository as a remote (this can be a URL or a directory)
git remote add origin /path/to/original/repo

# fetch the tag, which will include the entire repo and history up to that point
git fetch origin refs/tags/tmptag

# reset the head of the repository
git reset --hard FETCH_HEAD

# you can now change back to the original repository and remove the temporary tag
cd original_repo
git tag -d tmptag

Hopefully this solution keeps working for a few more years! :-)

What does enctype='multipart/form-data' mean?

enctype='multipart/form-data is an encoding type that allows files to be sent through a POST. Quite simply, without this encoding the files cannot be sent through POST.

If you want to allow a user to upload a file via a form, you must use this enctype.

Convert character to ASCII numeric value in java

If you wanted to convert the entire string into concatenated ASCII values then you can use this -

    String str = "abc";  // or anything else

    StringBuilder sb = new StringBuilder();
    for (char c : str.toCharArray())
    sb.append((int)c);

    BigInteger mInt = new BigInteger(sb.toString());
    System.out.println(mInt);

wherein you will get 979899 as output.

Credit to this.

I just copied it here so that it would be convenient for others.

How to check if an object implements an interface?

For an instance

Character.Gorgon gor = new Character.Gorgon();

Then do

gor instanceof Monster

For a Class instance do

Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);

CORS Access-Control-Allow-Headers wildcard being ignored?

Support for wildcards in the Access-Control-Allow-Headers header was added to the living standard only in May 2016, so it may not be supported by all browsers. On browser which don't implement this yet, it must be an exact match: https://www.w3.org/TR/2014/REC-cors-20140116/#access-control-allow-headers-response-header

If you expect a large number of headers, you can read in the value of the Access-Control-Request-Headers header and echo that value back in the Access-Control-Allow-Headers header.

How should I set the default proxy to use default credentials?

From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.

The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.

If you wanted to use different proxy settings to the current user then you would need to code

WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);

or

WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);

You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call

webRequest.Proxy.GetProxy(new Uri("http://google.com.au")) to see the actual details of the proxy server that would be used.

There seems to be some debate about whether you can set webRequest.Proxy or WebRequest.DefaultWebProxy = null to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy() with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.

The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.

How do I enable MSDTC on SQL Server?

MSDTC must be enabled on both systems, both server and client.
Also, make sure that there isn't a firewall between the systems that blocks RPC.
DTCTest is a nice litt app that helps you to troubleshoot any other problems.

How do I trim a file extension from a String in Java?

Use a method in com.google.common.io.Files class if your project is already dependent on Google core library. The method you need is getNameWithoutExtension.

How do I refresh a DIV content?

To reload a section of the page, you could use jquerys load with the current url and specify the fragment you need, which would be the same element that load is called on, in this case #here:

function updateDiv()
{ 
    $( "#here" ).load(window.location.href + " #here" );
}
  • Don't disregard the space within the load element selector: + " #here"

This function can be called within an interval, or attached to a click event

How to stop a vb script running in windows

Start Task Manager, click on the Processes tab, right-click on wscript.exe and select End Process, and confirm in the dialog that follows. This will terminate the wscript.exe that is executing your script.

How to use SQL Order By statement to sort results case insensitive?

You can also do ORDER BY TITLE COLLATE NOCASE.

Edit: If you need to specify ASC or DESC, add this after NOCASE like

ORDER BY TITLE COLLATE NOCASE ASC

or

ORDER BY TITLE COLLATE NOCASE DESC

Reference list item by index within Django template?

A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

such as get my_list[x] in templates:

in template

{% load index %}
{{ my_list|index:x }}

templatetags/index.py

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

if my_list = [['a','b','c'], ['d','e','f']], you can use {{ my_list|index:x|index:y }} in template to get my_list[x][y]

It works fine with "for"

{{ my_list|index:forloop.counter0 }}

Tested and works well ^_^

how to calculate binary search complexity

ok see this
for(i=0;i<n;n=n/2)
{
i++;
}
1. Suppose at i=k the loop terminate. i.e. the loop execute k times.

2. at each iteration n is divided by half.

2.a n=n/2                   .... AT I=1
2.b n=(n/2)/2=n/(2^2)
2.c n=((n/2)/2)/2=n/(2^3)....... aT I=3
2.d n=(((n/2)/2)/2)/2=n/(2^4)

So at i=k , n=1 which is obtain by dividing n  2^k times
n=2^k
1=n/2^k 
k=log(N)  //base 2

How to use UIVisualEffectView to Blur Image?

I prefer creating Visual Effects via Storyboard - no code used for creating or maintaining UI Elements. It gives me full landscape support, too. I have made a little demo of using UIVisualEffects with Blur and also Vibrancy.

Demo on Github

Android Material and appcompat Manifest merger failed

As of Android P, the support libraries have been moved to AndroidX

Please do a refactor for your libs from this page.

https://developer.android.com/topic/libraries/support-library/refactor

How would you make two <div>s overlap?

With absolute or relative positioning, you can do all sorts of overlapping. You've probably want the logo to be styled as such:

div#logo {
  position: absolute;
  left: 100px; // or whatever
}

Note: absolute position has its eccentricities. You'll probably have to experiment a little, but it shouldn't be too hard to do what you want.

Encrypt and Decrypt in Java

If you use a static key, encrypt and decrypt always give the same result;

public static final String CRYPTOR_KEY = "your static key here";
byte[] keyByte = Base64.getDecoder().decode(CRYPTOR_KEY);
key = new SecretKeySpec(keyByte, "AES");

Node.js Mongoose.js string to ObjectId function

You can use this also

const { ObjectId } = require('mongodb');
const _id = ObjectId("4eb6e7e7e9b7f4194e000001");

it's simplest way to do it

How to select all rows which have same value in some column

SELECT * FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Update : for better performance and faster query its good to add e1 before *

SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Get the value of bootstrap Datetimepicker in JavaScript

Or try:

$("#datetimepicker").data().date;

How does "cat << EOF" work in bash?

POSIX 7

kennytm quoted man bash, but most of that is also POSIX 7: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07_04 :

The redirection operators "<<" and "<<-" both allow redirection of lines contained in a shell input file, known as a "here-document", to the input of a command.

The here-document shall be treated as a single word that begins after the next and continues until there is a line containing only the delimiter and a , with no characters in between. Then the next here-document starts, if there is one. The format is as follows:

[n]<<word
    here-document
delimiter

where the optional n represents the file descriptor number. If the number is omitted, the here-document refers to standard input (file descriptor 0).

If any character in word is quoted, the delimiter shall be formed by performing quote removal on word, and the here-document lines shall not be expanded. Otherwise, the delimiter shall be the word itself.

If no characters in word are quoted, all lines of the here-document shall be expanded for parameter expansion, command substitution, and arithmetic expansion. In this case, the in the input behaves as the inside double-quotes (see Double-Quotes). However, the double-quote character ( '"' ) shall not be treated specially within a here-document, except when the double-quote appears within "$()", "``", or "${}".

If the redirection symbol is "<<-", all leading <tab> characters shall be stripped from input lines and the line containing the trailing delimiter. If more than one "<<" or "<<-" operator is specified on a line, the here-document associated with the first operator shall be supplied first by the application and shall be read first by the shell.

When a here-document is read from a terminal device and the shell is interactive, it shall write the contents of the variable PS2, processed as described in Shell Variables, to standard error before reading each line of input until the delimiter has been recognized.

Examples

Some examples not yet given.

Quotes prevent parameter expansion

Without quotes:

a=0
cat <<EOF
$a
EOF

Output:

0

With quotes:

a=0
cat <<'EOF'
$a
EOF

or (ugly but valid):

a=0
cat <<E"O"F
$a
EOF

Outputs:

$a

Hyphen removes leading tabs

Without hyphen:

cat <<EOF
<tab>a
EOF

where <tab> is a literal tab, and can be inserted with Ctrl + V <tab>

Output:

<tab>a

With hyphen:

cat <<-EOF
<tab>a
<tab>EOF

Output:

a

This exists of course so that you can indent your cat like the surrounding code, which is easier to read and maintain. E.g.:

if true; then
    cat <<-EOF
    a
    EOF
fi

Unfortunately, this does not work for space characters: POSIX favored tab indentation here. Yikes.

What is PHPSESSID?

PHPSESSID is an auto generated session cookie by the server which contains a random long number which is given out by the server itself

Send POST request with JSON data using Volley

You can also send data by overriding getBody() method of JsonObjectRequest class. As shown below.

    @Override
    public byte[] getBody()
    {

        JSONObject jsonObject = new JSONObject();
        String body = null;
        try
        {
            jsonObject.put("username", "user123");
            jsonObject.put("password", "Pass123");

            body = jsonObject.toString();
        } catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try
        {
            return body.toString().getBytes("utf-8");
        } catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

Xcode 'CodeSign error: code signing is required'

Most common cause, considering that all certificates are installed properly is not specifying the Code Signing Identity in the Active Target settings along with the Project settings. Change these from to iPhone Developer (Xcode will select the right profile depending on App ID match).

  • In Xcode , change from Simulator to Device (in the dropdown at the top of the Xcode window), so that your target for application deployment will be the Device.

  • The default ID which is a wild card ID is like a catch all iD, when associated in Code Signing (if you are using sample files to build, they will most obviously not have com.coolapps.appfile imports, in which case without the 'Team Provisioning profile', your build would fail. So you would want to set this in your

  • Xcode->Project ->Edit Project Settings->Build (tab)->Code Signing Identity (header) ->Any iOS (change from Any iOS Simulator)->(select 'iPhone Developer' as value and it will default to the wildcard development provisioning profile (Team Provisioning Profile: * )

and also (VERY IMPORTANT)

  • Xcode->Project ->Edit Active Target ->Build (tab)->Code Signing Identity (header) ->Any iOS (change from Any iOS Simulator)->(select 'iPhone Developer' as value and it will default to the wildcard development provisioning profile (Team Provisioning Profile: * )

Complete steps for a beginner at: http://codevelle.wordpress.com/2010/12/21/moving-from-ios-simulator-to-the-ios-device-smoothly-without-code-sign-error/

Replace Multiple String Elements in C#

Another option using linq is

[TestMethod]
public void Test()
{
  var input = "it's worth a lot of money, if you can find a buyer.";
  var expected = "its worth a lot of money if you can find a buyer";
  var removeList = new string[] { ".", ",", "'" };
  var result = input;

  removeList.ToList().ForEach(o => result = result.Replace(o, string.Empty));

  Assert.AreEqual(expected, result);
}

How to verify if a file exists in a batch file?

Type IF /? to get help about if, it clearly explains how to use IF EXIST.

To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one

Finally copying just means calling COPY and calling another bat file can be done like this:

MYOTHERBATFILE.BAT sync.bat myprogram.ini

One-liner if statements, how to convert this if-else-statement

Since expression is boolean:

return expression;

Fire event on enter key press for a textbox

My 2c.. I have used javascript, but found it did things that were not quite expected.

USE the panel's defaultButton attribute/property as many of the above posts suggest. It is reliable (EASY) and works in all the browsers I have tested it on.

using .join method to convert array to string without commas

You can specify an empty string as an argument to join, if no argument is specified a comma is used.

 arr.join('');

http://jsfiddle.net/mowglisanu/CVr25/1/

Binding value to input in Angular JS

You don't need to set the value at all. ng-model takes care of it all:

  • set the input value from the model
  • update the model value when you change the input
  • update the input value when you change the model from js

Here's the fiddle for this: http://jsfiddle.net/terebentina/9mFpp/

Can I check if Bootstrap Modal Shown / Hidden?

In offical way:

> ($("element").data('bs.modal') || {})._isShown    // Bootstrap 4
> ($("element").data('bs.modal') || {}).isShown     // Bootstrap <= 3

{} is used to avoid the case that modal is not opened yet (it return undefined). You can also assign it equal {isShown: false} to keep it's more make sense.

Set the location in iPhone Simulator

In my delegate callback, I check to see if I'm running in a simulator (#if TARGET_ IPHONE_SIMULATOR) and if so, I supply my own, pre-looked-up, Lat/Long. To my knowledge, there's no other way.

Java: Instanceof and Generics

Technically you shouldn't have to, that's the point of generics, so you can do compile-type checking:

public int indexOf(E arg0) {
   ...
}

but then the @Override may be a problem if you have a class hierarchy. Otherwise see Yishai's answer.

Check if ADODB connection is open

ADO Recordset has .State property, you can check if its value is adStateClosed or adStateOpen

If Not (rs Is Nothing) Then
  If (rs.State And adStateOpen) = adStateOpen Then rs.Close
  Set rs = Nothing
End If

MSDN about State property

Edit; The reason not to check .State against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen check.

Edit2:

For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum

If Not (rs Is Nothing) Then
  If (rs.State And 1) = 1 Then rs.Close
  Set rs = Nothing
End If

Or you can define the constant yourself to make your code more readable (defining them all for a good example.)

Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.    

[...]

If Not (rs Is Nothing) Then

    ' ex. If (0001 And 0001) = 0001 (only open flag) -> true
    ' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
    '    This second example means it is open, but its value is not 1
    '    and If rs.State = 1 -> false, even though it is open
    If (rs.State And adStateOpen) = adStateOpen Then 
        rs.Close
    End If

    Set rs = Nothing
End If

Post multipart request with Android SDK

Remove all your httpclient, httpmime dependency and add this dependency compile 'commons-httpclient:commons-httpclient:3.1'. This dependency has built in MultipartRequestEntity so that you can easily upload one or more files to the server

public class FileUploadUrlConnection extends AsyncTask<String, String, String> {
private Context context;
private String url;
private List<File> files;

public FileUploadUrlConnection(Context context, String url, List<File> files) {
    this.context = context;
    this.url = url;
    this.files = files;
}

@Override
protected String doInBackground(String... params) {

    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(url);
    HttpClientParams connectionParams = new HttpClientParams();

    post.setRequestHeader(// Your header goes here );

    try {
        Part[] parts = new Part[files.size()];
        for (int i=0; i<files.size(); i++) {
            Part part = new FilePart(files.get(i).getName(), files.get(i));
            parts[i] = part;
        }

        MultipartRequestEntity entity = new MultipartRequestEntity(parts, connectionParams);

        post.setRequestEntity(entity);

        int statusCode = client.executeMethod(post);
        String response = post.getResponseBodyAsString();

        Log.v("Multipart "," "+response);
        if(statusCode == 200) {
            return response;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } 
 return null;
}

You can also add the request and response timeout

client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);

html5 input for money/currency

Well in the end I had to compromise by implementing a HTML5/CSS solution, forgoing increment buttons in IE (they're a bit broke in FF anyway!), but gaining number validation that the JQuery spinner doesn't provide. Though I have had to go with a step of whole numbers.

_x000D_
_x000D_
span.gbp {_x000D_
    float: left;_x000D_
    text-align: left;_x000D_
}_x000D_
_x000D_
span.gbp::before {_x000D_
    float: left;_x000D_
    content: "\00a3"; /* £ */_x000D_
    padding: 3px 4px 3px 3px;_x000D_
}_x000D_
_x000D_
span.gbp input {_x000D_
     width: 280px !important;_x000D_
}
_x000D_
<label for="broker_fees">Broker Fees</label>_x000D_
<span class="gbp">_x000D_
    <input type="number" placeholder="Enter whole GBP (&pound;) or zero for none" min="0" max="10000" step="1" value="" name="Broker_Fees" id="broker_fees" required="required" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

The validation is a bit flaky across browsers, where IE/FF allow commas and decimal places (as long as it's .00), where as Chrome/Opera don't and want just numbers.

I guess it's a shame that the JQuery spinner won't work with a number type input, but the docs explicitly state not to do that :-( and I'm puzzled as to why a number spinner widget allows input of any ascii char?

@Transactional(propagation=Propagation.REQUIRED)

In Spring applications, if you enable annotation based transaction support using <tx:annotation-driven/> and annotate any class/method with @Transactional(propagation=Propagation.REQUIRED) then Spring framework will start a transaction and executes the method and commits the transaction. If any RuntimeException occurred then the transaction will be rolled back.

Actually propagation=Propagation.REQUIRED is default propagation level, you don't need to explicitly mentioned it.

For further info : http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations

ToList()-- does it create a new list?

A new list is created but the items in it are references to the orginal items (just like in the original list). Changes to the list itself are independent, but to the items will find the change in both lists.

jQuery UI Tabs - How to Get Currently Selected Tab Index

If you want to ensure ui.newTab.index() is available in all situations (local and remote tabs), then call it in the activate function as the documentation says:

$("#tabs").tabs({
        activate: function(event, ui){
             alert(ui.newTab.index());
             // You can also use this to set another tab, see fiddle...
             // $("#other-tabs").tabs("option", "active", ui.newTab.index());                   
        },
});

http://jsfiddle.net/7v7n0v3j/

Get User's Current Location / Coordinates

you should do those steps:

  1. add CoreLocation.framework to BuildPhases -> Link Binary With Libraries (no longer necessary as of XCode 7.2.1)
  2. import CoreLocation to your class - most likely ViewController.swift
  3. add CLLocationManagerDelegate to your class declaration
  4. add NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription to plist
  5. init location manager:

    locationManager = CLLocationManager()
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
    
  6. get User Location By:

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
    

cmake - find_library - custom library location

The simplest solution may be to add HINTS to each find_* request.

For example:

find_library(CURL_LIBRARY
    NAMES curl curllib libcurl_imp curllib_static
    HINTS "${CMAKE_PREFIX_PATH}/curl/lib"
)

For Boost I would strongly recommend using the FindBoost standard module and setting the BOOST_DIR variable to point to your Boost libraries.

How can I get the username of the logged-in user in Django?

You can use the request object to find the logged in user

def my_view(request):
    username = None
    if request.user.is_authenticated():
        username = request.user.username

According to https://docs.djangoproject.com/en/2.0/releases/1.10/

In version Django 2.0 the syntax has changed to

request.user.is_authenticated

Where can I view Tomcat log files in Eclipse?

Go to the "Server" view, then double-click the Tomcat server you're running. The access log files are stored relative to the path in the "Server path" field, which itself is relative to the workspace path.

find if an integer exists in a list of integers

You should be referencing Selected not ids.Contains as the last line.

I just realized this is a formatting issue, from the OP. Regardless you should be referencing the value in Selected. I recommend adding some Console.WriteLine calls to see exactly what is being printed out on each line and also what each value is.

After your update: ids is an empty list, how is this not throwing a NullReferenceException? As it was never initialized in that code block

An attempt was made to access a socket in a way forbidden by its access permissions

Not surprisingly, this error can arise when another process is listening on the desired port. This happened today when I started an instance of the Apache Web server, listening on its default port (80), having forgotten that I already had IIS 7 running, and listening on that port. This is well explained in Port 80 is being used by SYSTEM (PID 4), what is that? Better yet, that article points to Stop http.sys from listening on port 80 in Windows, which explains a very simple way to resolve it, with just a tad of help from an elevated command prompt and a one-line edit of my hosts file.

Python: Converting string into decimal number

If you are converting price (in string) to decimal price then....

from decimal import Decimal

price = "14000,45"
price_in_decimal = Decimal(price.replace(',','.'))

No need for the replace if your strings already use dots as a decimal separator

How to run a single RSpec test?

Run the commands from your project's root directory:

# run all specs in the project's spec folder
bundle exec rspec 

# run specs nested under a directory, like controllers
bundle exec rspec spec/controllers

# run a single test file
bundle exec rspec spec/controllers/groups_controller_spec.rb

# run a test or subset of tests within a file
# e.g., if the 'it', 'describe', or 'context' block you wish to test
# starts at line 45, run:
bundle exec rspec spec/controllers/groups_controller_spec.rb:45

Difference between long and int data types

A typical best practice is not using long/int/short directly. Instead, according to specification of compilers and OS, wrap them into a header file to ensure they hold exactly the amount of bits that you want. Then use int8/int16/int32 instead of long/int/short. For example, on 32bit Linux, you could define a header like this

typedef char int8;
typedef short int16;
typedef int int32;
typedef unsigned int uint32;

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

Catch multiple exceptions at once?

Wanted to added my short answer to this already long thread. Something that hasn't been mentioned is the order of precedence of the catch statements, more specifically you need to be aware of the scope of each type of exception you are trying to catch.

For example if you use a "catch-all" exception as Exception it will preceed all other catch statements and you will obviously get compiler errors however if you reverse the order you can chain up your catch statements (bit of an anti-pattern I think) you can put the catch-all Exception type at the bottom and this will be capture any exceptions that didn't cater for higher up in your try..catch block:

            try
            {
                // do some work here
            }
            catch (WebException ex)
            {
                // catch a web excpetion
            }
            catch (ArgumentException ex)
            {
                // do some stuff
            }
            catch (Exception ex)
            {
                // you should really surface your errors but this is for example only
                throw new Exception("An error occurred: " + ex.Message);
            }

I highly recommend folks review this MSDN document:

Exception Hierarchy

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

?php

/* Database config */

$db_host        = 'localhost';
$db_user        = '~';
$db_pass        = '~';
$db_database    = 'banners'; 

/* End config */


$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

?>

Javascript, viewing [object HTMLInputElement]

If the element is an <input type="text">, you should query the value attribute:

alert(element.value);

See an example in this jsFiddle.

Also, and seeing you're starting to learn HTML, you might consider using console.log() instead of alert() for debugging purposes. It doesn't interrupt the execution flow of the script, and you can have a general view of all logs in almost every browser with developer tools (except that one, obviously).

And of course, you could consider using a web development tool like Firebug, for instance, which is a powerful addon for Firefox that provides a lot of functionalities (debugging javascript code, DOM inspector, real-time DOM/CSS changes, request monitoring ...)

SQL Server Case Statement when IS NULL

CASE WHEN B.[STAT] IS NULL THEN (C.[EVENT DATE]+10)   -- Type DATETIME
     ELSE '-'                                         -- Type VARCHAR
     END AS [DATE]

You need to select one type or the other for the field, the field type can't vary by row. The simplest is to remove the ELSE '-' and let it implicitly get the value NULL instead for the second case.

How to display images from a folder using php - PHP

You have two ways to do that:

METHOD 1. The secure way.

Put the images on /www/htdocs/

<?php
    $www_root = 'http://localhost/images';
    $dir = '/var/www/images';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

METHOD 2. Unsecure but more flexible.

Put the images on any directory (apache must have permission to read the file).

<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

And create another script to read the image file.

<?php
    $filename = base64_decode($_GET['file']);
    // Check the folder location to avoid exploit
    if (dirname($filename) == '/home/user/Pictures')
        echo file_get_contents($filename);
?>

How do I print to the debug output window in a Win32 app?

You can also use WriteConsole method to print on console.

AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);

Convert RGB to Black & White in OpenCV

AFAIK, you have to convert it to grayscale and then threshold it to binary.

1. Read the image as a grayscale image If you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:

// C
IplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

// C++ (OpenCV 2.0)
Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

2. Convert an RGB image im_rgb into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image

// C
IplImage *im_rgb  = cvLoadImage("image.jpg");
IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);
cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);

// C++
Mat im_rgb  = imread("image.jpg");
Mat im_gray;
cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

3. Convert to binary You can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.

E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):

// C
IplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);
cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

// C++
Mat img_bw = im_gray > 128;

In the above example, 128 is the threshold.

4. Save to disk

// C
cvSaveImage("image_bw.jpg",img_bw);

// C++
imwrite("image_bw.jpg", img_bw);

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

Chrome print is usually an extension page so there is no dom attachment happening in your existing page. You can trigger the print command using command line apis(window.print()) but then they have not provided apis for closing it becoz of vary reason like choosing print options, print machine,count etc.

How to pass data from child component to its parent in ReactJS?

Considering React Function Components and using Hooks are getting more popular these days , I will give a simple example of how to Passing data from child to parent component

in Parent Function Component we will have :

import React, { useState, useEffect } from "react";

then

const [childData, setChildData] = useState("");

and passing setChildData (which do a job similar to this.setState in Class Components) to Child

return( <ChildComponent passChildData={setChildData} /> )

in Child Component first we get the receiving props

function ChildComponent(props){ return (...) }

then you can pass data anyhow like using a handler function

const functionHandler = (data) => {

props.passChildData(data);

}

How can I easily convert DataReader to List<T>?

I would (and have) started to use Dapper. To use your example would be like (written from memory):

public List<CustomerEntity> GetCustomerList()
{
    using (DbConnection connection = CreateConnection())
    {
        return connection.Query<CustomerEntity>("procToReturnCustomers", commandType: CommandType.StoredProcedure).ToList();
    }
}

CreateConnection() would handle accessing your db and returning a connection.

Dapper handles mapping datafields to properties automatically. It also supports multiple types and result sets and is very fast.

Query returns IEnumerable hence the ToList().

Cannot find mysql.sock

I can't help with question #1, but to refresh locate's file database, run:

updatedb

Reading an Excel file in PHP

I use PHP-ExcelReader to read xls files, and works great.

Spring MVC: How to return image in @ResponseBody?

It's work for me in Spring 4.

@RequestMapping(value = "/image/{id}", method = RequestMethod.GET)
public void findImage(@PathVariable("id") String id, HttpServletResponse resp){

        final Foto anafoto = <find object>
        resp.reset();
        resp.setContentType(MediaType.IMAGE_JPEG_VALUE);
        resp.setContentLength(anafoto.getImage().length);

        final BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(anafoto.getImageInBytes()));

        try {
            FileCopyUtils.copy(in, resp.getOutputStream());
            resp.flushBuffer();
        } catch (final IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

How do I pass a datetime value as a URI parameter in asp.net mvc?

The colon in your first example's url is going to cause an error (Bad Request) so you can't do exactly what you are looking for. Other than that, using a DateTime as an action parameter is most definitely possible.

If you are using the default routing, this 3rd portion of your example url is going to pickup the DateTime value as the {id} parameter. So your Action method might look like this:

public ActionResult Index(DateTime? id)
{
    return View();
}

You'll probably want to use a Nullable Datetime as I have, so if this parameter isn't included it won't cause an exception. Of course, if you don't want it to be named "id" then add another route entry replacing {id} with your name of choice.

As long as the text in the url will parse to a valid DateTime value, this is all you have to do. Something like the following works fine and will be picked up in your Action method without any errors:

<%=Html.ActionLink("link", "Index", new { id = DateTime.Now.ToString("dd-MM-yyyy") }) %>

The catch, in this case of course, is that I did not include the time. I'm not sure there are any ways to format a (valid) date string with the time not represented with colons, so if you MUST include the time in the url, you may need to use your own format and parse the result back into a DateTime manually. Say we replace the colon with a "!" in the actionlink: new { id = DateTime.Now.ToString("dd-MM-yyyy HH!mm") }.

Your action method will fail to parse this as a date so the best bet in this case would probably to accept it as a string:

public ActionResult Index(string id)
{
    DateTime myDate;
    if (!string.IsNullOrEmpty(id))
    {
        myDate = DateTime.Parse(id.Replace("!", ":"));
    }
    return View();
}

Edit: As noted in the comments, there are some other solutions arguably better than mine. When I originally wrote this answer I believe I was trying to preserve the essence of the date time format as best possible, but clearly URL encoding it would be a more proper way of handling this. +1 to Vlad's comment.

Printing integer variable and string on same line in SQL

declare @x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
    
PRINT 'There are ' + CAST(@x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */

JavaScript dictionary with names

I suggest not using an array unless you have multiple objects to consider. There isn't anything wrong this statement:

var myMappings = {
    "Name": 0.1,
    "Phone": 0.1,
    "Address": 0.5,
    "Zip": 0.1,
    "Comments": 0.2
};

for (var col in myMappings) {
    alert((myMappings[col] * 100) + "%");
}

How to set java_home on Windows 7?

You may wanna look into Windows/System32 folder for the following files: - java.exe - javaw.exe - javaws.exe

Because, the path variable is including these files, you can get a headache trying to figure out why the java -version or javac -version keeps pointing to the old JAVA_HOME: rename those files, take out the extension with an underscore, for instance. And then, you only will have to create the JAVA_HOME variable, add it to the path variable (e.g., %JAVA_HOME%) and append the "\bin" particle. This way you need to only change the JAVA_HOME variable pointing to different JRE or JDK and have multiple installations of java just by setting JAVA_HOME.

This also means that it is better to install Java manually, without an installer, so you are able to toy with it.

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

You might be missing a DNS server conf in /etc/resolv.conf

make sure u can ping to: ping pypi.python.org

if you're not getting a ping try to add a DNS server to file...something like:

nameserver xxx.xxx.xxx.xxx

Python not working in the command line of git bash

The one worked for me is as mentioned earlier in these great answers above is the alias as follows: (I'm using anaconda, so first find where is the python path, then add it into the alias on git bash). 1. on anaconda terminal I run: where python 2. on git bash I run: alias python='winpty "C:\ProgramData\Anaconda3\envs\your_env_name\python.exe"' 3. Done. Python is defined inside the git Bash using the alias.

Thanks to (Vitaliy Terziev & hygull) for their very helpful answers.

How to create a custom navigation drawer in android

I need to add a header to categorize the list item in Drawer

Customize the listView or use expandableListView

I need a radio button to select some of my options

You can do that without modifying the current implementation of NavigationDrawer, You just need to create a custom adapter for your listView. You can add a parent layout as Drawer then you can do any complex layouts within that as normal.

Difference between BYTE and CHAR in column datatypes

I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.

Also those field types might be treated differently in regard to accented characters or case, for example 'binaryField(ete) = "été"' will not match while 'charField(ete) = "été"' might (again not sure about Oracle).

Pass Method as Parameter using C#

class PersonDB
{
  string[] list = { "John", "Sam", "Dave" };
  public void Process(ProcessPersonDelegate f)
  {
    foreach(string s in list) f(s);
  }
}

The second class is Client, which will use the storage class. It has a Main method that creates an instance of PersonDB, and it calls that object’s Process method with a method that is defined in the Client class.

class Client
{
  static void Main()
  {
    PersonDB p = new PersonDB();
    p.Process(PrintName);
  }
  static void PrintName(string name)
  {
    System.Console.WriteLine(name);
  }
}

How does delete[] know it's an array?

You cannot use delete for an array, and you cannot use delete [] for a non-array.

docker mounting volumes on host

Let me add my own answer, because I believe the others are missing the point of Docker.

Using VOLUME in the Dockerfile is the Right Way™, because you let Docker know that a certain directory contains permanent data. Docker will create a volume for that data and never delete it, even if you remove all the containers that use it.

It also bypasses the union file system, so that the volume is in fact an actual directory that gets mounted (read-write or readonly) in the right place in all the containers that share it.

Now, in order to access that data from the host, you only need to inspect your container:

# docker inspect myapp
[{
    .
    .
    .
    "Volumes": {
        "/var/www": "/var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6...",
        "/var/cache/nginx": "/var/lib/docker/vfs/dir/62499e6b31cb3f7f59bf00d8a16b48d2...",
        "/var/log/nginx": "/var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87..."
    },
    "VolumesRW": {
        "/var/www": false,
        "/var/cache/nginx": true,
        "/var/log/nginx": true
    }
}]

What I usually do is make symlinks in some standard place such as /srv, so that I can easily access the volumes and manage the data they contain (only for the volumes you care about):

ln -s /var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6... /srv/myapp-www
ln -s /var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87... /srv/myapp-log

Enum to String C++

Kind of an anonymous lookup table rather than a long switch statement:

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];

Check existence of input argument in a Bash shell script

In my case the only working solution to check if last arguments exists is:

if [[ "$7" == '' ]] ; then
  echo "error"
  exit
fi

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

How to go back last page

I made a button I can reuse anywhere on my app.

Create this component

import { Location } from '@angular/common';
import { Component, Input } from '@angular/core';

@Component({
    selector: 'back-button',
    template: `<button mat-button (click)="goBack()" [color]="color">Back</button>`,
})
export class BackButtonComponent {
    @Input()color: string;

  constructor(private location: Location) { }

  goBack() {
    this.location.back();
  }
}

Then add it to any template when you need a back button.

<back-button color="primary"></back-button>

Note: This is using Angular Material, if you aren't using that library then remove the mat-button and color.

How to hash a string into 8 digits?

I am sharing our nodejs implementation of the solution as implemented by @Raymond Hettinger.

var crypto = require('crypto');
var s = 'she sells sea shells by the sea shore';
console.log(BigInt('0x' + crypto.createHash('sha1').update(s).digest('hex'))%(10n ** 8n));

how do I insert a column at a specific column index in pandas?

If you want a single value for all rows:

df.insert(0,'name_of_column','')
df['name_of_column'] = value

Edit:

You can also:

df.insert(0,'name_of_column',value)

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

jQuery datepicker years shown

If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years" demo , and hit view source:

$("#restricting").datepicker({ 
    yearRange: "-20:+0", // this is the option you're looking for
    showOn: "both", 
    buttonImage: "templates/images/calendar.gif", 
    buttonImageOnly: true 
});

You'll want to do the same (obviously changing -20 to -100 or something).

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Here is the solutions that worked for me:

  1. open index.php from the htdocs folder
  2. inside replace the word dashboard with your database name.
  3. restart the server

This should resolve the issue :-)

is there any IE8 only css hack?

Doing something like this should work for you.

<!--[if IE 8]> 
<div id="IE8">
<![endif]--> 

*Your content* 

<!--[if IE 8]> 
</div>
<![endif]--> 

Then your CSS can look like this:

#IE8 div.something
{ 
    color: purple; 
}

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

If you just want to disable App Transport Policy for local dev servers then the following solutions work well. It's useful when you're unable, or it's impractical, to set up HTTPS (e.g. when using the Google App Engine dev server).

As others have said though, ATP should definitely not be turned off for production apps.

1) Use a different plist for Debug

Copy your Plist file and NSAllowsArbitraryLoads. Use this Plist for debugging.

XCode Debug

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

2) Exclude local servers

Alternatively, you can use a single plist file and exclude specific servers. However, it doesn't look like you can exclude IP 4 addresses so you might need to use the server name instead (found in System Preferences -> Sharing, or configured in your local DNS).

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>server.local</key>
        <dict/>
        <key>NSExceptionAllowsInsecureHTTPLoads</key>
        <true/>
    </dict>
</dict>

How to write MySQL query where A contains ( "a" or "b" )

Two options:

  1. Use the LIKE keyword, along with percent signs in the string

    select * from table where field like '%a%' or field like '%b%'.
    

    (note: If your search string contains percent signs, you'll need to escape them)

  2. If you're looking for more a complex combination of strings than you've specified in your example, you could regular expressions (regex):

    See the MySQL manual for more on how to use them: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Of these, using LIKE is the most usual solution -- it's standard SQL, and in common use. Regex is less commonly used but much more powerful.

Note that whichever option you go with, you need to be aware of possible performance implications. Searching for sub-strings like this will mean that the query will have to scan the entire table. If you have a large table, this could make for a very slow query, and no amount of indexing is going to help.

If this is an issue for you, and you'r going to need to search for the same things over and over, you may prefer to do something like adding a flag field to the table which specifies that the string field contains the relevant sub-strings. If you keep this flag field up-to-date when you insert of update a record, you could simply query the flag when you want to search. This can be indexed, and would make your query much much quicker. Whether it's worth the effort to do that is up to you, it'll depend on how bad the performance is using LIKE.

What is Node.js?

Q: The programming model is event driven, especially the way it handles I/O.

Correct. It uses call-backs, so any request to access the file system would cause a request to be sent to the file system and then Node.js would start processing its next request. It would only worry about the I/O request once it gets a response back from the file system, at which time it will run the callback code. However, it is possible to make synchronous I/O requests (that is, blocking requests). It is up to the developer to choose between asynchronous (callbacks) or synchronous (waiting).

Q: It uses JavaScript and the parser is V8.

Yes

Q: It can be easily used to create concurrent server applications.

Yes, although you'd need to hand-code quite a lot of JavaScript. It might be better to look at a framework, such as http://www.easynodejs.com/ - which comes with full online documentation and a sample application.

C++ array initialization

Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++.

Since this initalizer is universal, for bool array you don't really need a different "syntax". 0 works as an initializer for bool type as well, so

bool myBoolArray[ARRAY_SIZE] = { 0 };

is guaranteed to initialize the entire array with false. As well as

char* myPtrArray[ARRAY_SIZE] = { 0 };

in guaranteed to initialize the whole array with null-pointers of type char *.

If you believe it improves readability, you can certainly use

bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };

but the point is that = { 0 } variant gives you exactly the same result.

However, in C++ = { 0 } might not work for all types, like enum types, for example, which cannot be initialized with integral 0. But C++ supports the shorter form

T myArray[ARRAY_SIZE] = {};

i.e. just an empty pair of {}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.

navbar color in Twitter Bootstrap

If you are using LESS, you can use Mixins for less code. Here I will add a gradient, border, and border-radius:

.navbar-inner {
  #gradient > .vertical(#ffffff, #ECECEC);
  border: #E2E2E2;
  .border-radius(6px);
}

*If you are using the rails gem, twitter-bootstrap-rails, I do this directly in the file bootstrap_and_overrides.css.less*

How to prevent text in a table cell from wrapping

<th nowrap="nowrap">

or

<th style="white-space:nowrap;">

or

<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>

How to sort by dates excel?

If you dont want to format a separate column with you normal dates pasted to it -- do the following -- add a column to the extreme left of your data and reverve your date ie if the date you had already entered was for example 11.5.16 enter int he new lefthand column 160511 ( notice that there are numbers only and no full stops . When you now sort there will be no mix ups as you have encountered.i have used this method for over 30 years and it never lets me down. And as you have placed the date by year, month and day you neednt include that column if you want or need tu print out your complete list.

Read tab-separated file line into array

You're very close:

while IFS=$'\t' read -r -a myArray
do
 echo "${myArray[0]}"
 echo "${myArray[1]}"
 echo "${myArray[2]}"
done < myfile

(The -r tells read that \ isn't special in the input data; the -a myArray tells it to split the input-line into words and store the results in myArray; and the IFS=$'\t' tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)

How to check if iframe is loaded or it has a content?

You can use the iframe's load event to respond when the iframe loads.

document.querySelector('iframe').onload = function(){
    console.log('iframe loaded');
};

This won't tell you whether the correct content loaded: To check that, you can inspect the contentDocument.

document.querySelector('iframe').onload = function(){
    var iframeBody = this.contentDocument.body;
    console.log('iframe loaded, body is: ', body);
};

Checking the contentDocument won't work if the iframe src points to a different domain from where your code is running.

java.io.IOException: Invalid Keystore format

You may corrupt the file during copy/transfer.

Are you using maven? If you are copying keystore file with "filter=true", you may corrupt the file.

Please check the file size.

C# Numeric Only TextBox Control

You can check the Ascii value by e.keychar on KeyPress event of TextBox.

By checking the AscII value you can check for number or character.

Similarly you can write logic to check the Email ID.

Google Maps API v3: How to remove all markers?

You need to set map null to that marker.

var markersList = [];    

function removeMarkers(markersList) {
   for(var i = 0; i < markersList.length; i++) {
      markersList[i].setMap(null);
   }
}

function addMarkers() {
   var marker = new google.maps.Marker({
        position : {
            lat : 12.374,
            lng : -11.55
        },
        map : map
       });
      markersList.push(marker);
   }

Socket accept - "Too many open files"

Similar issue on Ubuntu 18 on vsphere. The cause - Config file nginx.conf contains too many log files and sockets. Sockets are treated as files in Linux. When nginx -s reload or sudo service nginx start/restart, the Too many open files error appeared in error.log.

NGINX worker processes were launched by NGINX user. Ulimit (soft and hard) for nginx user was 65536. The ulimit and setting limits.conf did not work.

The rlimit setting in nginx.conf did not help either: worker_rlimit_nofile 65536;

The solution that worked was:

$ mkdir -p /etc/systemd/system/nginx.service.d
$ nano /etc/systemd/system/nginx.service.d/nginx.conf
    [Service]
    LimitNOFILE=30000
$ systemctl daemon-reload
$ systemctl restart nginx.service

How to execute a Windows command on a remote PC?

This can be done by using PsExec which can be downloaded here

psexec \\computer_name -u username -p password ipconfig

If this isn't working try doing this :-

  1. Open RegEdit on your remote server.
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.

  3. Add a new DWORD value called LocalAccountTokenFilterPolicy

  4. Set its value to 1.
  5. Reboot your remote server.
  6. Try running PSExec again from your local server.

How to make String.Contains case insensitive?

You can create your own extension method to do this:

public static bool Contains(this string source, string toCheck, StringComparison comp)
  {
    return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
  }

And then call:

 mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);

Drop multiple tables in one shot in MySQL

A lazy way of doing this if there are alot of tables to be deleted.

  1. Get table using the below

    • For sql server - SELECT CONCAT(name,',') Table_Name FROM SYS.tables;
    • For oralce - SELECT CONCAT(TABLE_NAME,',') FROM SYS.ALL_TABLES;
  2. Copy and paste the table names from the result set and paste it after the DROP command.

python multithreading wait till all threads finished

From the threading module documentation

There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.

There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be join()ed. They are never deleted, since it is impossible to detect the termination of alien threads.

So, to catch those two cases when you are not interested in keeping a list of the threads you create:

import threading as thrd


def alter_data(data, index):
    data[index] *= 2


data = [0, 2, 6, 20]

for i, value in enumerate(data):
    thrd.Thread(target=alter_data, args=[data, i]).start()

for thread in thrd.enumerate():
    if thread.daemon:
        continue
    try:
        thread.join()
    except RuntimeError as err:
        if 'cannot join current thread' in err.args[0]:
            # catchs main thread
            continue
        else:
            raise

Whereupon:

>>> print(data)
[0, 4, 12, 40]

Graphical DIFF programs for linux

Diffuse is also very good. It even lets you easily adjust how lines are matched up, by defining match-points.

How to shift a block of code left/right by one space in VSCode?

No need to use any tool for that

  1. Set Tab Spaces to 1.
  2. Select whole block of code and then press Shift + Tab

Shift + Tab = Shift text right to left

Breaking out of a for loop in Java

How about

for (int k = 0; k < 10; k = k + 2) {
    if (k == 2) {
        break;
    }

    System.out.println(k);
}

The other way is a labelled loop

myloop:  for (int i=0; i < 5; i++) {

              for (int j=0; j < 5; j++) {

                if (i * j > 6) {
                  System.out.println("Breaking");
                  break myloop;
                }

                System.out.println(i + " " + j);
              }
          }

For an even better explanation you can check here

How to permanently export a variable in Linux?

A particular example: I have Java 7 and Java 6 installed, I need to run some builds with 6, others with 7. Therefore I need to dynamically alter JAVA_HOME so that maven picks up what I want for each build. I did the following:

  • created j6.sh script which simply does export JAVA_HOME=... path to j6 install...
  • then, as suggested by one of the comments above, whenever I need J6 for a build, I run source j6.sh in that respective command terminal. By default, my JAVA_HOME is set to J7.

Hope this helps.

Save text file UTF-8 encoded with VBA

This writes a Byte Order Mark at the start of the file, which is unnecessary in a UTF-8 file and some applications (in my case, SAP) don't like it. Solution here: Can I export excel data with UTF-8 without BOM?

How to increase the timeout period of web service in asp.net?

you can do this in different ways:

  1. Setting a timeout in the web service caller from code (not 100% sure but I think I have seen this done);
  2. Setting a timeout in the constructor of the web service proxy in the web references;
  3. Setting a timeout in the server side, web.config of the web service application.

see here for more details on the second case:

http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14

and here for details on the last case:

How to increase the timeout to a web service request?

Display text on MouseOver for image in html

You can use title attribute.

<img src="smiley.gif"  title="Smiley face"/>

You can change the source of image as you want.

And as @Gray commented:

You can also use the title on other things like <a ... anchors, <p>, <div>, <input>, etc. See: this

How to embed a PDF?

<iframe src="http://docs.google.com/gview?url=http://domain.com/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

Google docs allows you to embed PDFs, Microsoft Office Docs, and other applications by just linking to their services with an iframe. Its user-friendly, versatile, and attractive.

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

How to call on a function found on another file?

Small addition to @user995502's answer on how to run the program.

g++ player.cpp main.cpp -o main.out && ./main.out

How can I perform a reverse string search in Excel without using VBA?

=RIGHT(A1,LEN(A1)-FIND("`*`",SUBSTITUTE(A1," ","`*`",LEN(A1)-LEN(SUBSTITUTE(A1," ",""))))) 

MySQL select 10 random rows from 600K rows fast

If you have just one Read-Request

Combine the answer of @redsio with a temp-table (600K is not that much):

DROP TEMPORARY TABLE IF EXISTS tmp_randorder;
CREATE TABLE tmp_randorder (id int(11) not null auto_increment primary key, data_id int(11));
INSERT INTO tmp_randorder (data_id) select id from datatable;

And then take a version of @redsios Answer:

SELECT dt.*
FROM
       (SELECT (RAND() *
                     (SELECT MAX(id)
                        FROM tmp_randorder)) AS id)
        AS rnd
 INNER JOIN tmp_randorder rndo on rndo.id between rnd.id - 10 and rnd.id + 10
 INNER JOIN datatable AS dt on dt.id = rndo.data_id
 ORDER BY abs(rndo.id - rnd.id)
 LIMIT 1;

If the table is big, you can sieve on the first part:

INSERT INTO tmp_randorder (data_id) select id from datatable where rand() < 0.01;

If you have many read-requests

  1. Version: You could keep the table tmp_randorder persistent, call it datatable_idlist. Recreate that table in certain intervals (day, hour), since it also will get holes. If your table gets really big, you could also refill holes

    select l.data_id as whole from datatable_idlist l left join datatable dt on dt.id = l.data_id where dt.id is null;

  2. Version: Give your Dataset a random_sortorder column either directly in datatable or in a persistent extra table datatable_sortorder. Index that column. Generate a Random-Value in your Application (I'll call it $rand).

    select l.*
    from datatable l 
    order by abs(random_sortorder - $rand) desc 
    limit 1;
    

This solution discriminates the 'edge rows' with the highest and the lowest random_sortorder, so rearrange them in intervals (once a day).

Regex to get the words after matching string

Here's a quick Perl script to get what you need. It needs some whitespace chomping.

#!/bin/perl

$sample = <<END;
Subject:
  Security ID:        S-1-5-21-3368353891-1012177287-890106238-22451
  Account Name:       ChamaraKer
  Account Domain:     JIC
  Logon ID:       0x1fffb

Object:
  Object Server:  Security
  Object Type:    File
  Object Name:    D:\\ApacheTomcat\\apache-tomcat-6.0.36\\logs\\localhost.2013- 07-01.log
  Handle ID:  0x11dc
END

my @sample_lines = split /\n/, $sample;
my $path;

foreach my $line (@sample_lines) {
  ($path) = $line =~ m/Object Name:([^s]+)/g;
  if($path) {
    print $path . "\n";
  }
}

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))