Programs & Examples On #Customdialog

How can I change default dialog button text color in android 5

Kotlin 2020: Very simple method

After dialog.show() use:

dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(requireContext(), R.color.yourColor))

File loading by getClass().getResource()

The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

How to change theme for AlertDialog

In Dialog.java (Android src) a ContextThemeWrapper is used. So you could copy the idea and do something like:

AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));

And then style it like you want:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AlertDialogCustom" parent="@android:style/Theme.Dialog">
        <item name="android:textColor">#00FF00</item>
        <item name="android:typeface">monospace</item>
        <item name="android:textSize">10sp</item>
    </style>
</resources>

Using Excel as front end to Access database (with VBA)

It's quite easy and efficient to use Excel as a reporting tool for Access data. A quick "non programming" approach is to set a List or a Pivot Table, linked to your External Data source. But that's out of scope for Stackoverflow.
A programmatic approach can be very simple:

strProv = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & SourceFile & ";"
Set cnn = New ADODB.Connection  
cnn.Open strProv
Set rst = New ADODB.Recordset
rst.Open strSql, cnn
myDestRange.CopyFromRecordset rst

That's it !

Application Crashes With "Internal Error In The .NET Runtime"

In my case this exception was occured when disk space was over and .NET can't allocate memory in Windows Virtual Memory.

In event log I saw this error:

Application popup: Windows - Virtual Memory Minimum Too Low : Your system is low on virtual memory. Windows is increasing the size of your virtual memory paging file. During this process, memory requests for some applications may be denied.

And previous error:

The C: disk is at or near capacity. You may need to delete some files.

Android emulator: How to monitor network traffic?

Yes, wireshark will work.

I don't think there is any easy way to filter out solely emulator traffic, since it is coming from the same src IP.

Perhaps the best way would be to set up a very bare VMware environment and only run the emulator in there, at least that way there wouldn't be too much background traffic.

How do I filter query objects by date range in Django?

To make it more flexible, you can design a FilterBackend as below:

class AnalyticsFilterBackend(generic_filters.BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        predicate = request.query_params # or request.data for POST

        if predicate.get('from_date', None) is not None and predicate.get('to_date', None) is not None:
            queryset = queryset.filter(your_date__range=(predicate['from_date'], predicate['to_date']))

        if predicate.get('from_date', None) is not None and predicate.get('to_date', None) is None:
            queryset = queryset.filter(your_date__gte=predicate['from_date'])

        if predicate.get('to_date', None) is not None and predicate.get('from_date', None) is None:
            queryset = queryset.filter(your_date__lte=predicate['to_date'])
        return queryset

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Cannot use object of type stdClass as array?

It's not an array, it's an object of type stdClass.

You can access it like this:

echo $oResult->context;

More info here: What is stdClass in PHP?

What is PAGEIOLATCH_SH wait type in SQL Server?

From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

Select * from <table> where <col1> = <value> order by <PrimaryKey>

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

How do I compare two strings in Perl?

In addtion to Sinan Ünür comprehensive listing of string comparison operators, Perl 5.10 adds the smart match operator.

The smart match operator compares two items based on their type. See the chart below for the 5.10 behavior (I believe this behavior is changing slightly in 5.10.1):

perldoc perlsyn "Smart matching in detail":

The behaviour of a smart match depends on what type of thing its arguments are. It is always commutative, i.e. $a ~~ $b behaves the same as $b ~~ $a . The behaviour is determined by the following table: the first row that applies, in either order, determines the match behaviour.

  $a      $b        Type of Match Implied    Matching Code
  ======  =====     =====================    =============
  (overloading trumps everything)

  Code[+] Code[+]   referential equality     $a == $b   
  Any     Code[+]   scalar sub truth         $b->($a)   

  Hash    Hash      hash keys identical      [sort keys %$a]~~[sort keys %$b]
  Hash    Array     hash slice existence     grep {exists $a->{$_}} @$b
  Hash    Regex     hash key grep            grep /$b/, keys %$a
  Hash    Any       hash entry existence     exists $a->{$b}

  Array   Array     arrays are identical[*]
  Array   Regex     array grep               grep /$b/, @$a
  Array   Num       array contains number    grep $_ == $b, @$a 
  Array   Any       array contains string    grep $_ eq $b, @$a 

  Any     undef     undefined                !defined $a
  Any     Regex     pattern match            $a =~ /$b/ 
  Code()  Code()    results are equal        $a->() eq $b->()
  Any     Code()    simple closure truth     $b->() # ignoring $a
  Num     numish[!] numeric equality         $a == $b   
  Any     Str       string equality          $a eq $b   
  Any     Num       numeric equality         $a == $b   

  Any     Any       string equality          $a eq $b   

+ - this must be a code reference whose prototype (if present) is not ""
(subs with a "" prototype are dealt with by the 'Code()' entry lower down) 
* - that is, each element matches the element of same index in the other
array. If a circular reference is found, we fall back to referential 
equality.   
! - either a real number, or a string that looks like a number

The "matching code" doesn't represent the real matching code, of course: it's just there to explain the intended meaning. Unlike grep, the smart match operator will short-circuit whenever it can.

Custom matching via overloading You can change the way that an object is matched by overloading the ~~ operator. This trumps the usual smart match semantics. See overload.

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

Simplest way to achieve pretty logging in Preethi Jain szenario:

LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
loggingInInterceptor.setPrettyLogging(true);
LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
loggingOutInterceptor.setPrettyLogging(true);
factory.getInInterceptors().add(loggingInInterceptor);
factory.getOutInterceptors().add(loggingOutInterceptor);

jQuery click event not working after adding class

Based on @Arun P Johny this is how you do it for an input:

<input type="button" class="btEdit" id="myButton1">

This is how I got it in jQuery:

$(document).on('click', "input.btEdit", function () {
    var id = this.id;
    console.log(id);
});

This will log on the console: myButton1. As @Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.

UPDATE

Though it would be better to say:

$(document).on('click', "input.btEdit", function () {
    var id = $(this).id;
    console.log(id);
});

Since this is JQuery's syntax, even though both will work.

What is the best way to modify a list in a 'foreach' loop?

The best approach from a performance perspective is probably to use a one or two arrays. Copy the list to an array, do operations on the array, and then build a new list from the array. Accessing an array element is faster than accessing a list item, and conversions between a List<T> and a T[] can use a fast "bulk copy" operation which avoids the overhead associated accessing individual items.

For example, suppose you have a List<string> and wish to have every string in the list which starts with T be followed by an item "Boo", while every string that starts with "U" is dropped entirely. An optimal approach would probably be something like:

int srcPtr,destPtr;
string[] arr;

srcPtr = theList.Count;
arr = new string[srcPtr*2];
theList.CopyTo(arr, theList.Count); // Copy into second half of the array
destPtr = 0;
for (; srcPtr < arr.Length; srcPtr++)
{
  string st = arr[srcPtr];
  char ch = (st ?? "!")[0]; // Get first character of string, or "!" if empty
  if (ch != 'U')
    arr[destPtr++] = st;
  if (ch == 'T')
    arr[destPtr++] = "Boo";
}
if (destPtr > arr.Length/2) // More than half of dest. array is used
{
  theList = new List<String>(arr); // Adds extra elements
  if (destPtr != arr.Length)
    theList.RemoveRange(destPtr, arr.Length-destPtr); // Chop to proper length
}
else
{
  Array.Resize(ref arr, destPtr);
  theList = new List<String>(arr); // Adds extra elements
}

It would have been helpful if List<T> provided a method to construct a list from a portion of an array, but I'm unaware of any efficient method for doing so. Still, operations on arrays are pretty fast. Of note is the fact that adding and removing items from the list does not require "pushing" around other items; each item gets written directly to its appropriate spot in the array.

AngularJS - Any way for $http.post to send request parameters instead of JSON?

I think the params config parameter won't work here since it adds the string to the url instead of the body but to add to what Infeligo suggested here is an example of the global override of a default transform (using jQuery param as an example to convert the data to param string).

Set up global transformRequest function:

var app = angular.module('myApp');

app.config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return $.param(data);
    }
});

That way all calls to $http.post will automatically transform the body to the same param format used by the jQuery $.post call.

Note you may also want to set the Content-Type header per call or globally like this:

$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

Sample non-global transformRequest per call:

    var transform = function(data){
        return $.param(data);
    }

    $http.post("/foo/bar", requestData, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        transformRequest: transform
    }).success(function(responseData) {
        //do stuff with response
    });

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

How to filter (key, value) with ng-repeat in AngularJs?

My solution would be create custom filter and use it:

app.filter('with', function() {
  return function(items, field) {
        var result = {};
        angular.forEach(items, function(value, key) {
            if (!value.hasOwnProperty(field)) {
                result[key] = value;
            }
        });
        return result;
    };
});

And in html:

 <div ng-repeat="(k,v) in items | with:'secId'">
        {{k}} {{v.pos}}
 </div>

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Tokenizing strings in C

int not_in_delimiter(char c, char *delim){

    while(*delim != '\0'){
            if(c == *delim) return 0;
            delim++;
    }
    return 1;
}

char *token_separater(char *source, char *delimiter, char **last){

char *begin, *next_token;
char *sbegin;

/*Get the start of the token */
if(source)
  begin = source;
else
  begin = *last;

sbegin = begin;

/*Scan through the string till we find character in delimiter. */
while(*begin != '\0' && not_in_delimiter(*begin, delimiter)){
       begin++;
}

/* Check if we have reached at of the string */
if(*begin == '\0') {
/* We dont need to come further, hence return NULL*/
   *last = NULL;
    return sbegin;
}
/* Scan the string till we find a character which is not in delimiter */
 next_token  = begin;
 while(next_token != '\0' && !not_in_delimiter(*next_token, delimiter))    {
    next_token++;
 }
 /* If we have not reached at the end of the string */
 if(*next_token != '\0'){
  *last = next_token--;
  *next_token = '\0';
   return sbegin;
}
}

 void main(){

    char string[10] = "abcb_dccc";
    char delim[10] = "_";
    char *token = NULL;
    char *last = "" ;
    token  = token_separater(string, delim, &last);
    printf("%s\n", token);
    while(last){
            token  = token_separater(NULL, delim, &last);
            printf("%s\n", token);
    }

}

You can read detail analysis at blog mentioned in my profile :)

Returning IEnumerable<T> vs. IQueryable<T>

Yes, both use deferred execution. Let's illustrate the difference using the SQL Server profiler....

When we run the following code:

MarketDevEntities db = new MarketDevEntities();

IEnumerable<WebLog> first = db.WebLogs;
var second = first.Where(c => c.DurationSeconds > 10);
var third = second.Where(c => c.WebLogID > 100);
var result = third.Where(c => c.EmailAddress.Length > 11);

Console.Write(result.First().UserName);

In SQL Server profiler we find a command equal to:

"SELECT * FROM [dbo].[WebLog]"

It approximately takes 90 seconds to run that block of code against a WebLog table which has 1 million records.

So, all table records are loaded into memory as objects, and then with each .Where() it will be another filter in memory against these objects.

When we use IQueryable instead of IEnumerable in the above example (second line):

In SQL Server profiler we find a command equal to:

"SELECT TOP 1 * FROM [dbo].[WebLog] WHERE [DurationSeconds] > 10 AND [WebLogID] > 100 AND LEN([EmailAddress]) > 11"

It approximately takes four seconds to run this block of code using IQueryable.

IQueryable has a property called Expression which stores a tree expression which starts being created when we used the result in our example (which is called deferred execution), and at the end this expression will be converted to an SQL query to run on the database engine.

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

How can one check to see if a remote file exists using PHP?

function remote_file_exists($url){
   return(bool)preg_match('~HTTP/1\.\d\s+200\s+OK~', @current(get_headers($url)));
}  
$ff = "http://www.emeditor.com/pub/emed32_11.0.5.exe";
    if(remote_file_exists($ff)){
        echo "file exist!";
    }
    else{
        echo "file not exist!!!";
    }

What is in your .vimrc?

My favorite bit of my .vimrc is a set of mappings for working with macros:

nnoremap <Leader>qa mqGo<Esc>"ap
nnoremap <Leader>qb mqGo<Esc>"bp
nnoremap <Leader>qc mqGo<Esc>"cp
<SNIP>
nnoremap <Leader>qz mqGo<Esc>"zp

nnoremap <Leader>Qa G0"ad$dd'q
nnoremap <Leader>Qb G0"bd$dd'q
nnoremap <Leader>Qc G0"cd$dd'q
<SNIP>
nnoremap <Leader>Qz G0"zd$dd'q

With this \q[a-z] will mark your location, and print the contents of the given register at the bottom of the current file and \Q[a-z] will put the contents of the last line into the given register and go back to your marked location. Makes it really easy to edit a macro or copy and tweak one macro into a new register.

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

Powershell get ipv4 address into a variable

(Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DefaultIPGateway -ne $null}).IPAddress | select-object -first 1

Android ImageView Animation

imgDics = (ImageView) v.findViewById(R.id.img_player_tab2_dics);
    imgDics.setOnClickListener(onPlayer2Click);
    anim = new RotateAnimation(0f, 360f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                            0.5f);
    anim.setInterpolator(new LinearInterpolator());
    anim.setRepeatCount(Animation.INFINITE);
    anim.setDuration(4000);

    // Start animating the image
    imgDics.startAnimation(anim);

Sort a list of lists with a custom compare function

Also, your compare function is incorrect. It needs to return -1, 0, or 1, not a boolean as you have it. The correct compare function would be:

def compare(item1, item2):
    if fitness(item1) < fitness(item2):
        return -1
    elif fitness(item1) > fitness(item2):
        return 1
    else:
        return 0

# Calling
list.sort(key=compare)

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException in Netty means your game server tries to send data to a client, but that client has closed connection to your server.

And that exception is not the only one! There're several others. See BadClientSilencer in Xitrum. I had to add that to prevent those errors from messing my log file.

How to make an autocomplete address field with google maps api?

I really doubt it--google maps API is great for geocoding known addresses, but it generally return data that is suitable for autocomplete-style operations. Nevermind the challenge of not hitting the API in such a way as to eat up your geocoding query limit very quickly.

How to add manifest permission to an application?

If you are using the Eclipse ADT plugin for your development, open AndroidManifest.xml in the Android Manifest Editor (should be the default action for opening AndroidManifest.xml from the project files list).

Afterwards, select the Permissions tab along the bottom of the editor (Manifest - Application - Permissions - Instrumentation - AndroidManifest.xml), then click Add... a Uses Permission and select the desired permission from the dropdown on the right, or just copy-paste in the necessary one (such as the android.permission.INTERNET permission you required).

nodeJS - How to create and read session with express

Hello I am trying to add new session values in node js like

req.session.portal = false
Passport.authenticate('facebook', (req, res, next) => {
    next()
})(req, res, next)

On passport strategies I am not getting portal value in mozilla request but working fine with chrome and opera

FacebookStrategy: new PassportFacebook.Strategy({
    clientID: Configuration.SocialChannel.Facebook.AppId,
    clientSecret: Configuration.SocialChannel.Facebook.AppSecret,
    callbackURL: Configuration.SocialChannel.Facebook.CallbackURL,
    profileFields: Configuration.SocialChannel.Facebook.Fields,
    scope: Configuration.SocialChannel.Facebook.Scope,
    passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
    console.log(JSON.stringify(req.session));

How to add image to canvas

In my case, I was mistaken the function parameters, which are:

context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);

If you expect them to be

context.drawImage(image, width, height);

you will place the image just outside the canvas with the same effects as described in the question.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

This happens when your result is not a result (but a "false" instead). You should change this line

$sql = 'SELECT * FROM $usertable WHERE PartNumber = $partid';

to this:

$sql = "SELECT * FROM $usertable WHERE PartNumber = $partid";

because the " can interprete $variables while ' cannot.

Works fine with integers (numbers), for strings you need to put the $variable in single quotes, like

$sql = "SELECT * FROM $usertable WHERE PartNumber = '$partid' ";

If you want / have to work with single quotes, then php CAN NOT interprete the variables, you will have to do it like this:

 $sql = 'SELECT * FROM '.$usertable.' WHERE string_column = "'.$string.'" AND integer_column = '.$number.';

How to make an unaware datetime timezone aware in python

I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.

If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object. This is not the case.

the replace( tzinfo=... ) seems to be random in its behaviour. It is therefore useless. Do not use this!

localize is the correct function to use. Example:

localdatetime_aware = tz.localize(datetime_nonaware)

Or a more complete example:

import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())

gives me a timezone aware datetime value of the current local time:

datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)

Disable sorting on last column when using jQuery DataTables

Read here

http://www.craiglotter.co.za/2010/04/19/how-to-disable-sorting-on-a-column-in-jquery-datatables-plugin/

$('#example').dataTable({
    "aoColumns": [
        null,
        null,
        { "bSortable": false }, // <-- disable sorting for column 3
        null
     ]
});

http://datatables.net/usage/columns under bSortable You can specify which columns to disable using aoColumnDefs and aTargets

$('#example').dataTable({
    "aoColumnDefs": [
        { 
          "bSortable": false, 
          "aTargets": [ -1 ] // <-- gets last column and turns off sorting
         } 
     ]
});        

http://live.datatables.net/aqoxob/edit#source

How to disable XDebug

If you are using MAMP Pro on Mac OS X it's done via the MAMP client by unchecking Activate Xdebug under the PHP tab:

Disabling Xdebug in MAMP Pro

How to call controller from the button click in asp.net MVC 4

Try this:

@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)

in your code should be,

@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})

Swift - How to convert String to Double

Swift 4.0

try this

 let str:String = "111.11"
 let tempString = (str as NSString).doubleValue
 print("String:-",tempString)

NoClassDefFoundError on Maven dependency

I was able to work around it by running mvn install:install-file with -Dpackaging=class. Then adding entry to POM as described here:

The right way of setting <a href=""> when it's a local file

Organize your files in hierarchical directories and then just use relative paths.

Demo:

HTML (index.html)

<a href='inner/file.html'>link</a>

Directory structure:

base/
base/index.html
base/inner/file.html
....

Java best way for string find and replace?

One possibility, reducing the longer form before expanding all:

string.replaceAll("Milan Vasic", "Milan").replaceAll("Milan", "Milan Vasic")

Another way, treating Vasic as optional:

string.replaceAll("Milan( Vasic)?", "Milan Vasic")

Others have described solutions based on lookahead or alternation.

How do I restrict a float value to only two places after the decimal point in C?

If you just want to round the number for output purposes, then the "%.2f" format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:

#include <math.h>

float val = 37.777779;

float rounded_down = floorf(val * 100) / 100;   /* Result: 37.77 */
float nearest = roundf(val * 100) / 100;  /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100;      /* Result: 37.78 */

Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.

As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.

For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.

Should I learn C before learning C++?

i think c is a really nice programming language, it's compact and somewhat easy to learn. but if you only want to learn c++ start with c++. but i suggest you to learn both. and if you want to do that; i think it's better to start with c. as said before: it's small and somewhat easy to learn. might be a nice step-up to a more complex programming language as c++. (since c provides you with some basics)

good luck.

How do I save a String to a text file using Java?

import java.io.*;

private void stringToFile( String text, String fileName )
 {
 try
 {
    File file = new File( fileName );

    // if file doesnt exists, then create it 
    if ( ! file.exists( ) )
    {
        file.createNewFile( );
    }

    FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
    BufferedWriter bw = new BufferedWriter( fw );
    bw.write( text );
    bw.close( );
    //System.out.println("Done writing to " + fileName); //For testing 
 }
 catch( IOException e )
 {
 System.out.println("Error: " + e);
 e.printStackTrace( );
 }
} //End method stringToFile

You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.

Disallow Twitter Bootstrap modal window from closing

Just add these two things

data-backdrop="static" 
data-keyboard="false"

It will look like this now

<div class="modal fade bs-example-modal-sm" id="myModal" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">

It will disable the escape button and also the click anywhere and hide.

How to wait for a number of threads to complete?

Depending on your needs, you may also want to check out the classes CountDownLatch and CyclicBarrier in the java.util.concurrent package. They can be useful if you want your threads to wait for each other, or if you want more fine-grained control over the way your threads execute (e.g., waiting in their internal execution for another thread to set some state). You could also use a CountDownLatch to signal all of your threads to start at the same time, instead of starting them one by one as you iterate through your loop. The standard API docs have an example of this, plus using another CountDownLatch to wait for all threads to complete their execution.

Why is printing "B" dramatically slower than printing "#"?

Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # = 6.03 seconds
  2. Second Matrix: O and B = 50.97 seconds

Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B");
        }
        if(j%100==0){               //Adding a line break in second loop      
            System.out.println();
        }                    
    }
    System.out.println("");                
}

Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings

C++ - unable to start correctly (0xc0150002)

In our case (next to trying Dependency Walker) it was a faulty manifest file, mixing 64 bits and 32 bits. We use two extra files while running in Debug mode: dbghelp.dll and Microsoft.DTfW.DHL.manifest. The manifest file looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- $Id -->
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <noInheritable />
    <assemblyIdentity type="win32" name="Microsoft.DTfW.DHL" version="6.11.1.404" processorArchitecture="x86" />
    <file name="dbghelp.dll" />
</assembly>

Notice the 'processorArchitecture' field. It was set to "amd64" instead of "x86". It's probably not always the cause, but in our case it was the root cause, so it may be helpful to some. For 64-bit runs, you'll want "amd64" in there.

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

html/css buttons that scroll down to different div sections on a webpage

try this:

<input type="button" onClick="document.getElementById('middle').scrollIntoView();" />

Find non-ASCII characters in varchar columns using SQL Server

running the various solutions on some real world data - 12M rows varchar length ~30, around 9k dodgy rows, no full text index in play, the patIndex solution is the fastest, and it also selects the most rows.

(pre-ran km. to set the cache to a known state, ran the 3 processes, and finally ran km again - the last 2 runs of km gave times within 2 seconds)

patindex solution by Gerhard Weiss -- Runtime 0:38, returns 9144 rows

select dodgyColumn from myTable fcc
WHERE  patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,dodgyColumn ) >0

the substring-numbers solution by MT. -- Runtime 1:16, returned 8996 rows

select dodgyColumn from myTable fcc
INNER JOIN dbo.Numbers32k dn ON dn.number<(len(fcc.dodgyColumn ))
WHERE ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))<32 
    OR ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))>127

udf solution by Deon Robertson -- Runtime 3:47, returns 7316 rows

select dodgyColumn 
from myTable 
where dbo.udf_test_ContainsNonASCIIChars(dodgyColumn , 1) = 1

Where are the Android icon drawables within the SDK?

You can find android drawables icons from the example path below...

C:\Users\User\AppData\Local\Android\sdk\platforms\android-25\data\res\drawable-xhdpi

Set a default parameter value for a JavaScript function

Use this if you want to use latest ECMA6 syntax:

_x000D_
_x000D_
function myFunction(someValue = "This is DEFAULT!") {_x000D_
  console.log("someValue --> ", someValue);_x000D_
}_x000D_
_x000D_
myFunction("Not A default value") // calling the function without default value_x000D_
myFunction()  // calling the function with default value
_x000D_
_x000D_
_x000D_

It is called default function parameters. It allows formal parameters to be initialized with default values if no value or undefined is passed. NOTE: It wont work with Internet Explorer or older browsers.

For maximum possible compatibility use this:

_x000D_
_x000D_
function myFunction(someValue) {_x000D_
  someValue = (someValue === undefined) ? "This is DEFAULT!" : someValue;_x000D_
  console.log("someValue --> ", someValue);_x000D_
}_x000D_
_x000D_
myFunction("Not A default value") // calling the function without default value_x000D_
myFunction()  // calling the function with default value
_x000D_
_x000D_
_x000D_

Both functions have exact same behavior as each of these example rely on the fact that the parameter variable will be undefined if no parameter value was passed when calling that function.

How can I change a file's encoding with vim?

Just like your steps, setting fileencoding should work. However, I'd like to add one "set bomb" to help editor consider the file as UTF8.

$ vim file
:set bomb
:set fileencoding=utf-8
:wq

What does git push -u mean?

"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull or git push without arguments. A little bit down, this article explains and demonstrates this concept.

Function to check if a string is a date

Easiest way to check if a string is a date:

if(strtotime($date_string)){
    // it's in date format
}

Docker Compose wait for container X before starting Y

Tried many different ways, but liked the simplicity of this: https://github.com/ufoscout/docker-compose-wait

The idea that you can use ENV vars in the docker compose file to submit a list of services hosts (with ports) which should be "awaited" like this: WAIT_HOSTS: postgres:5432, mysql:3306, mongo:27017.

So let's say you have the following docker-compose.yml file (copy/past from repo README):

version: "3"

services:

  mongo:
    image: mongo:3.4
    hostname: mongo
    ports:
      - "27017:27017"

  postgres:
    image: "postgres:9.4"
    hostname: postgres
    ports:
      - "5432:5432"

  mysql:
    image: "mysql:5.7"
    hostname: mysql
    ports:
      - "3306:3306"

  mySuperApp:
    image: "mySuperApp:latest"
    hostname: mySuperApp
    environment:
      WAIT_HOSTS: postgres:5432, mysql:3306, mongo:27017

Next, in order for services to wait, you need to add the following two lines to your Dockerfiles (into Dockerfile of the services which should await other services to start):

ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.5.0/wait /wait
RUN chmod +x /wait

The complete example of such sample Dockerfile (again from the project repo README):

FROM alpine

## Add your application to the docker image
ADD MySuperApp.sh /MySuperApp.sh

## Add the wait script to the image
ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.5.0/wait /wait
RUN chmod +x /wait

## Launch the wait tool and then your application
CMD /wait && /MySuperApp.sh

For other details about possible usage see README

Use Toast inside Fragment

To help another people with my same problem, the complete answer to Use Toast inside Fragment is:

Activity activity = getActivity();

@Override
public void onClick(View arg0) {

    Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}

Datatable to html Table

If your'e using Web Forms then Grid View can work very nicely for this

The code looks a little like this.

aspx page.

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name,Size,Quantity,Amount,Duration"></asp:GridView>

You can either input the data manually or use the source method in the code side

public class Room
{
    public string Name
    public double Size {get; set;}
    public int Quantity {get; set;}
    public double Amount {get; set;}
    public int Duration {get; set;}
}

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)//this is so you can keep any data you want for the list
    {
        List<Room> rooms=new List<Room>();
        //then use the rooms.Add() to add the rooms you need.
        GridView1.DataSource=rooms
        GridView1.Databind()
    }
}

Personally I like MVC4 the client side code ends up much lighter than Web Forms. It is similar to the above example with using a class but you use a view and Controller instead.

The View would look like this.

@model YourProject.Model.IEnumerable<Room>

<table>
    <th>
        <td>@Html.LabelFor(model => model.Name)</td>
        <td>@Html.LabelFor(model => model.Size)</td>
        <td>@Html.LabelFor(model => model.Quantity)</td>
        <td>@Html.LabelFor(model => model.Amount)</td>
        <td>@Html.LabelFor(model => model.Duration)</td>
   </th>
foreach(item in model)
{
    <tr>
        <td>@model.Name</td>
        <td>@model.Size</td>
        <td>@model.Quantity</td>
        <td>@model.Amount</td>
        <td>@model.Duration</td>
   </tr>
}
</table>

The controller might look something like this.

public ActionResult Index()
{
    List<Room> rooms=new List<Room>();
    //again add the items you need

    return View(rooms);
}

Hope this helps :)

how can the textbox width be reduced?

<input type="text" style="width:50px;"/>

Table cell widths - fixing width, wrapping/truncating long words

If you want to the long text wrapped properly in new lines then in your table id call use a css property table-layout:fixed; otherwise simply css can't break the long text in new lines.

How can I send large messages with Kafka (over 15MB)?

For people using landoop kafka: You can pass the config values in the environment variables like:

docker run -d --rm -p 2181:2181 -p 3030:3030 -p 8081-8083:8081-8083  -p 9581-9585:9581-9585 -p 9092:9092
 -e KAFKA_TOPIC_MAX_MESSAGE_BYTES=15728640 -e KAFKA_REPLICA_FETCH_MAX_BYTES=15728640  landoop/fast-data-dev:latest `

And if you're usind rdkafka then pass the message.max.bytes in the producer config like:

  const producer = new Kafka.Producer({
        'metadata.broker.list': 'localhost:9092',
        'message.max.bytes': '15728640',
        'dr_cb': true
    });

Similarly, for the consumer,

  const kafkaConf = {
   "group.id": "librd-test",
   "fetch.message.max.bytes":"15728640",
   ... .. }                                                                                                                                                                                                                                                      

Programmatically create a UIView with color gradient

extension UIView {

    func applyGradient(isVertical: Bool, colorArray: [UIColor]) { 
        layer.sublayers?.filter({ $0 is CAGradientLayer }).forEach({ $0.removeFromSuperlayer() })
         
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = colorArray.map({ $0.cgColor })
        if isVertical {
            //top to bottom
            gradientLayer.locations = [0.0, 1.0]
        } else {
            //left to right
            gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
            gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        }
        
        backgroundColor = .clear
        gradientLayer.frame = bounds
        layer.insertSublayer(gradientLayer, at: 0)
    }

}

USAGE

someView.applyGradient(isVertical: true, colorArray: [.green, .blue])

How to find all trigger associated with a table with SQL Server?

You Can View All trigger related to your database by below query

select * from sys.triggers

And for open trigger you can use below syntax

sp_helptext 'dbo.trg_InsertIntoUserTable'

SQL Server - Convert date field to UTC

If they're all local to you, then here's the offset:

SELECT GETDATE() AS CurrentTime, GETUTCDATE() AS UTCTime

and you should be able to update all the data using:

UPDATE SomeTable
   SET DateTimeStamp = DATEADD(hh, DATEDIFF(hh, GETDATE(), GETUTCDATE()), DateTimeStamp)

Would that work, or am I missing another angle of this problem?

Can't import database through phpmyadmin file size too large

If you are using MySQL in Xampp then do the steps below.

Find the following in XAMPP control panel>Apach-Config> PHP (php.ini) file

  • post_max_size = 8M

  • upload_max_filesize = 2M

  • max_execution_time = 30
  • ut_time = 60enter code here memory_limit = 8M

And change their sizes according to your need. I'm using these values

post_max_size = 30M
upload_max_filesize = 30M
max_execution_time = 4500
max_input_time = 4500
memory_limit = 850M

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

Parse rfc3339 date strings in Python?

You can use dateutil.parser.parse (install with python -m pip install python-dateutil) to parse strings into datetime objects.

dateutil.parser.parse will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime which you supply a format string to (see Brent Washburne's answer).

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

print(b.weekday())
# 1 (equal to a Tuesday)

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

Streams are often accessed by threads that periodically empty their content and, for example, display it on the screen, send it to a socket or write it to a file. This is done for performance reasons. Flushing an output stream means that you want to stop, wait for the content of the stream to be completely transferred to its destination, and then resume execution with the stream empty and the content sent.

How can I rename a project folder from within Visual Studio?

I have written a small tool that automates all these steps. It also supports Subversion for now.

Information about current releases can be found at Visual Studio Project Renamer Infos.

The latest releases can now be downloaded from the Visual Studio Project Renamer Download Page.

Feedback is much appreciated.

Conditionally ignoring tests in JUnit 4

The JUnit way is to do this at run-time is org.junit.Assume.

 @Before
 public void beforeMethod() {
     org.junit.Assume.assumeTrue(someCondition());
     // rest of setup.
 }

You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

An assumption failure causes the test to be ignored.

Edit: To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

@Test
public void calculateTotalSalary() {
    assumeThat(Database.connect(), is(notNull()));
    //test code below.
}

Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

In your app's build.gradle add the following:

android {
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}

Enforces Gradle to only compile the version number you state for all dependencies, no matter which version number the dependencies have stated.

"Invalid signature file" when attempting to run a .jar

For those who got this error when trying to create a shaded uber-jar with maven-shade-plugin, the solution is to exclude manifest signature files by adding the following lines to the plugin configuration:

<configuration>
    <filters>
        <filter>
            <artifact>*:*</artifact>
            <excludes>
                <exclude>META-INF/*.SF</exclude>
                <exclude>META-INF/*.DSA</exclude>
                <exclude>META-INF/*.RSA</exclude>
            </excludes>
        </filter>
    </filters>
    <!-- Additional configuration. -->
</configuration>

Launching Spring application Address already in use

Configure another port number(eg:8181) in /src/main/resources/application.properties

server.port=8181

error: This is probably not a problem with npm. There is likely additional logging output above

Check if port you want to run your app is free. For me, it was the problem.

Check if application is on its first run

This might help you

public class FirstActivity extends Activity {

    SharedPreferences sharedPreferences = null;
    Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        sharedPreferences = getSharedPreferences("com.myAppName", MODE_PRIVATE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (sharedPreferences.getBoolean("firstRun", true)) {
         //You can perform anything over here. This will call only first time
                 editor = sharedPreferences.edit();
                 editor.putBoolean("firstRun", false)
                 editor.commit();

        }
    }
}

Open window in JavaScript with HTML inserted

You can use window.open to open a new window/tab(according to browser setting) in javascript.

By using document.write you can write HTML content to the opened window.

Rotate image with javascript

CSS can be applied and you will have to set transform-origin correctly to get the applied transformation in the way you want

See the fiddle:

http://jsfiddle.net/OMS_/gkrsz/

Main code:

/* assuming that the image's height is 70px */

img.rotated {
    transform: rotate(90deg);
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -ms-transform: rotate(90deg);

    transform-origin: 35px 35px;
    -webkit-transform-origin: 35px 35px;
    -moz-transform-origin: 35px 35px;
    -ms-transform-origin: 35px 35px;
}

jQuery and JS:

$(img)
    .css('transform-origin-x', imgWidth / 2)
    .css('transform-origin-y', imgHeight / 2);

// By calculating the height and width of the image in the load function

// $(img).css('transform-origin', (imgWidth / 2) + ' ' + (imgHeight / 2) );

Logic:

Divide the image's height by 2. The transform-x and transform-y values should be this value

Link:

transform-origin at CSS | MDN

How to set a class attribute to a Symfony2 form input

You can add it in the options of your form class:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\MyEntity',
        'attr' => array(
            'class' => 'form-horizontal'
        )
    ));
}

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();

Get JSF managed bean by name in any Servlet related class

Have you tried an approach like on this link? I'm not sure if createValueBinding() is still available but code like this should be accessible from a plain old Servlet. This does require to bean to already exist.

http://www.coderanch.com/t/211706/JSF/java/access-managed-bean-JSF-from

 FacesContext context = FacesContext.getCurrentInstance();  
 Application app = context.getApplication();
 // May be deprecated
 ValueBinding binding = app.createValueBinding("#{" + expr + "}"); 
 Object value = binding.getValue(context);

Python Matplotlib Y-Axis ticks on Right Side of Plot

For right labels use ax.yaxis.set_label_position("right"), i.e.:

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()

Database design for a survey

You may choose to store the whole form as a JSON string.

Not sure about your requirement, but this approach would work in some circumstances.

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

Use index in pandas to plot data

You can use reset_index to turn the index back into a column:

monthly_mean.reset_index().plot(x='index', y='A')

Comparison of DES, Triple DES, AES, blowfish encryption for data

The encryption methods described are symmetric key block ciphers.

Data Encryption Standard (DES) is the predecessor, encrypting data in 64-bit blocks using a 56 bit key. Each block is encrypted in isolation, which is a security vulnerability.

Triple DES extends the key length of DES by applying three DES operations on each block: an encryption with key 0, a decryption with key 1 and an encryption with key 2. These keys may be related.

DES and 3DES are usually encountered when interfacing with legacy commercial products and services.

AES is considered the successor and modern standard. http://en.wikipedia.org/wiki/Advanced_Encryption_Standard

I believe the use of Blowfish is discouraged.

It is highly recommended that you do not attempt to implement your own cryptography and instead use a high-level implementation such as GPG for data at rest or SSL/TLS for data in transit. Here is an excellent and sobering video on encryption vulnerabilities http://rdist.root.org/2009/08/06/google-tech-talk-on-common-crypto-flaws/

Call a "local" function within module.exports from another function in module.exports?

You can also do this to make it more concise and readable. This is what I've seen done in several of the well written open sourced modules:

var self = module.exports = {

  foo: function (req, res, next) {
    return ('foo');
  },

  bar: function(req, res, next) {
    self.foo();
  }

}

Writing File to Temp Folder

You can dynamically retrieve a temp path using as following and better to use it instead of using hard coded string value for temp location.It will return the temp folder or temp file as you want.

string filePath = Path.Combine(Path.GetTempPath(),"SaveFile.txt");

or

Path.GetTempFileName();

How do I view events fired on an element in Chrome DevTools?

  • Hit F12 to open Dev Tools
  • Click the Sources tab
  • On right-hand side, scroll down to "Event Listener Breakpoints", and expand tree
  • Click on the events you want to listen for.
  • Interact with the target element, if they fire you will get a break point in the debugger

Similarly, you can right click on the target element -> select "inspect element" Scroll down on the right side of the dev frame, at the bottom is 'event listeners'. Expand the tree to see what events are attached to the element. Not sure if this works for events that are handled through bubbling (I'm guessing not)

How to make HTML open a hyperlink in another window or tab?

You should be able to add

target="_blank"

like

<a href="http://www.starfall.com/" target="_blank">Starfall</a>

How to indent a few lines in Markdown markup?

One way to do it is to use bullet points, which allows you specify multiple levels of indentation. Bullet points are inserted using multiples of two spaces, star, another space Eg.:

this is a normal line of text
  * this is the first level of bullet points, made up of <space><space>*<space>
    * this is more indented, composed of <space><space><space><space>*<space>

This method has the great advantage that it also makes sense when you view the raw text.

If you care about not seeing the bullet points themselves, you should (depending on where you're using markdown) to be able to add li {list-style-type: none;} to the css for the whole mark down area.

How to obtain Telegram chat_id for a specific user?

There is a bot that echoes your chat id upon starting a conversation.

Just search for @chatid_echo_bot and tap /start. It will echo your chat id.

Chat id bot screenshot

Another option is @getidsbot which gives you much more information. This bot also gives information about a forwarded message (from user, to user, chad ids, etc) if you forward the message to the bot.

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

How to install mechanize for Python 2.7?

Try this on Debian/Ubuntu:

sudo apt-get install python-mechanize

u'\ufeff' in Python string

This problem arise basically when you save your python code in a UTF-8 or UTF-16 encoding because python add some special character at the beginning of the code automatically (which is not shown by the text editors) to identify the encoding format. But, when you try to execute the code it gives you the syntax error in line 1 i.e, start of code because python compiler understands ASCII encoding. when you view the code of file using read() function you can see at the begin of the returned code '\ufeff' is shown. The one simplest solution to this problem is just by changing the encoding back to ASCII encoding(for this you can copy your code to a notepad and save it Remember! choose the ASCII encoding... Hope this will help.

Makefile to compile multiple C programs?

A simple program's compilation workflow is simple, I can draw it as a small graph: source -> [compilation] -> object [linking] -> executable. There are files (source, object, executable) in this graph, and rules (make's terminology). That graph is definied in the Makefile.

When you launch make, it reads Makefile, and checks for changed files. If there's any, it triggers the rule, which depends on it. The rule may produce/update further files, which may trigger other rules and so on. If you create a good makefile, only the necessary rules (compiler/link commands) will run, which stands "to next" from the modified file in the dependency path.

Pick an example Makefile, read the manual for syntax (anyway, it's clear for first sight, w/o manual), and draw the graph. You have to understand compiler options in order to find out the names of the result files.

The make graph should be as complex just as you want. You can even do infinite loops (don't do)! You can tell make, which rule is your target, so only the left-standing files will be used as triggers.

Again: draw the graph!.

Android offline documentation and sample codes

Write the following in linux terminal:

$ wget -r http://developer.android.com/reference/packages.html

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

Disable text input history

<input type="text" autocomplete="off" />

git: 'credential-cache' is not a git command

First find the version you are using for GIT.

using this command : git --version

if you have a newer version than 1.7.10.

Then simply use this this command.

Windows:

git config --global credential.helper wincred

MAC

git config --global credential.helper osxkeychain

Reference

How to remove close button on the jQuery UI dialog?

The best way to hide the button is to filter it with it's data-icon attribute:

$('#dialog-id [data-icon="delete"]').hide();

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

This should work in almost all browsers:

var xhr=new XMLHttpRequest();
xhr.open("GET","https://12Me21.github.io/test.txt");
xhr.onload=function(){
    console.log(xhr.responseText);
}
xhr.send();

Additionally, there's the new Fetch API:

fetch("https://12Me21.github.io/test.txt")
.then( response => response.text() )
.then( text => console.log(text) )

How to update single value inside specific array item in redux

In my case I did something like this, based on Luis's answer:

...State object...
userInfo = {
name: '...',
...
}

...Reducer's code...
case CHANGED_INFO:
return {
  ...state,
  userInfo: {
    ...state.userInfo,
    // I'm sending the arguments like this: changeInfo({ id: e.target.id, value: e.target.value }) and use them as below in reducer!
    [action.data.id]: action.data.value,
  },
};

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

Disable scrolling in an iPhone web application?

document.addEventListener('touchstart', function (e) {
    e.preventDefault();
});

Do not use the ontouchmove property to register the event handler as you are running at risk of overwriting an existing event handler(s). Use addEventListener instead (see the note about IE on the MDN page).

Beware that preventing default for the touchstart event on the window or document will disable scrolling of the descending areas.

To prevent the scrolling of the document but leave all the other events intact prevent default for the first touchmove event following touchstart:

var firstMove;

window.addEventListener('touchstart', function (e) {
    firstMove = true;
});

window.addEventListener('touchmove', function (e) {
    if (firstMove) {
        e.preventDefault();

        firstMove = false;
    }
});

The reason this works is that mobile Safari is using the first move to determine if body of the document is being scrolled. I have realised this while devising a more sophisticated solution.

In case this would ever stop working, the more sophisticated solution is to inspect the touchTarget element and its parents and make a map of directions that can be scrolled to. Then use the first touchmove event to detect the scroll direction and see if it is going to scroll the document or the target element (or either of the target element parents):

var touchTarget,
    touchScreenX,
    touchScreenY,
    conditionParentUntilTrue,
    disableScroll,
    scrollMap;

conditionParentUntilTrue = function (element, condition) {
    var outcome;

    if (element === document.body) {
        return false;
    }

    outcome = condition(element);

    if (outcome) {
        return true;
    } else {
        return conditionParentUntilTrue(element.parentNode, condition);
    }
};

window.addEventListener('touchstart', function (e) {
    touchTarget = e.targetTouches[0].target;
    // a boolean map indicating if the element (or either of element parents, excluding the document.body) can be scrolled to the X direction.
    scrollMap = {}

    scrollMap.left = conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollLeft > 0;
    });

    scrollMap.top = conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollTop > 0;
    });

    scrollMap.right = conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollWidth > element.clientWidth &&
               element.scrollWidth - element.clientWidth > element.scrollLeft;
    });

    scrollMap.bottom =conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollHeight > element.clientHeight &&
               element.scrollHeight - element.clientHeight > element.scrollTop;
    });

    touchScreenX = e.targetTouches[0].screenX;
    touchScreenY = e.targetTouches[0].screenY;
    disableScroll = false;
});

window.addEventListener('touchmove', function (e) {
    var moveScreenX,
        moveScreenY;

    if (disableScroll) {
        e.preventDefault();

        return;
    }

    moveScreenX = e.targetTouches[0].screenX;
    moveScreenY = e.targetTouches[0].screenY;

    if (
        moveScreenX > touchScreenX && scrollMap.left ||
        moveScreenY < touchScreenY && scrollMap.bottom ||
        moveScreenX < touchScreenX && scrollMap.right ||
        moveScreenY > touchScreenY && scrollMap.top
    ) {
        // You are scrolling either the element or its parent.
        // This will not affect document.body scroll.
    } else {
        // This will affect document.body scroll.

        e.preventDefault();

        disableScroll = true;
    }
});

The reason this works is that mobile Safari is using the first touch move to determine if the document body is being scrolled or the element (or either of the target element parents) and sticks to this decision.

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

ROWS UNBOUNDED PRECEDING is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY it defines the window on which the result is calculated.

Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.

Starting and ending rows might be fixed or relative to the current row based on the following keywords:

  • CURRENT ROW, the current row
  • UNBOUNDED PRECEDING, all rows before the current row -> fixed
  • UNBOUNDED FOLLOWING, all rows after the current row -> fixed
  • x PRECEDING, x rows before the current row -> relative
  • y FOLLOWING, y rows after the current row -> relative

Possible kinds of calculation include:

  • Both starting and ending row are fixed, the window consists of all rows of a partition, e.g. a Group Sum, i.e. aggregate plus detail rows
  • One end is fixed, the other relative to current row, the number of rows increases or decreases, e.g. a Running Total, Remaining Sum
  • Starting and ending row are relative to current row, the number of rows within a window is fixed, e.g. a Moving Average over n rows

So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING) results in a Cumulative Sum or Running Total

11 -> 11
 2 -> 11 +  2                = 13
 3 -> 13 +  3 (or 11+2+3)    = 16
44 -> 16 + 44 (or 11+2+3+44) = 60

How to read a line from a text file in c/c++?

getline() is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.

Assuming std namespace:

 ifstream file1("myfile.txt");
 string stuff;

 while (getline(file1, stuff, '\n')) {
      cout << stuff << endl;
 }

 file1.close();

Make a link open a new window (not tab)

You can try this:-

   <a href="some.htm" target="_blank">Link Text</a>

and you can try this one also:-

  <a href="some.htm" onclick="if(!event.ctrlKey&&!window.opera){alert('Hold the Ctrl Key');return false;}else{return true;}" target="_blank">Link Text</a>

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

Add my custom http header to Spring RestTemplate request / extend RestTemplate

If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer parameter can be used with a RestTemplateBuilder:

 String accessToken= "<the oauth 2 token>";
 RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
        request.getHeaders().add("Authorization", "Bearer "+accessToken);
        return execution.execute(request, body);
    })).build();

How to use the priority queue STL for objects?

A priority queue is an abstract data type that captures the idea of a container whose elements have "priorities" attached to them. An element of highest priority always appears at the front of the queue. If that element is removed, the next highest priority element advances to the front.

The C++ standard library defines a class template priority_queue, with the following operations:

push: Insert an element into the prioity queue.

top: Return (without removing it) a highest priority element from the priority queue.

pop: Remove a highest priority element from the priority queue.

size: Return the number of elements in the priority queue.

empty: Return true or false according to whether the priority queue is empty or not.

The following code snippet shows how to construct two priority queues, one that can contain integers and another one that can contain character strings:

#include <queue>

priority_queue<int> q1;
priority_queue<string> q2;

The following is an example of priority queue usage:

#include <string>
#include <queue>
#include <iostream>

using namespace std;  // This is to make available the names of things defined in the standard library.

int main()
{
    piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.

    pq.push("the quick");
    pq.push("fox");
    pq.push("jumped over");
    pq.push("the lazy dog");

    // The strings are ordered inside the priority queue in lexicographic (dictionary) order:
    // "fox", "jumped over", "the lazy dog", "the quick"
    //  The lowest priority string is "fox", and the highest priority string is "the quick"

    while (!pq.empty()) {
       cout << pq.top() << endl;  // Print highest priority string
       pq.pop();                    // Remmove highest priority string
    }

    return 0;
}

The output of this program is:

the quick
the lazy dog
jumped over
fox

Since a queue follows a priority discipline, the strings are printed from highest to lowest priority.

Sometimes one needs to create a priority queue to contain user defined objects. In this case, the priority queue needs to know the comparison criterion used to determine which objects have the highest priority. This is done by means of a function object belonging to a class that overloads the operator (). The overloaded () acts as < for the purpose of determining priorities. For example, suppose we want to create a priority queue to store Time objects. A Time object has three fields: hours, minutes, seconds:

struct Time {
    int h; 
    int m; 
    int s;
};

class CompareTime {
    public:
    bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
}

A priority queue to store times according the the above comparison criterion would be defined as follows:

priority_queue<Time, vector<Time>, CompareTime> pq;

Here is a complete program:

#include <iostream>
#include <queue>
#include <iomanip>

using namespace std;

struct Time {
    int h; // >= 0
    int m; // 0-59
    int s; // 0-59
};

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2)
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
};

int main()
{
    priority_queue<Time, vector<Time>, CompareTime> pq;

    // Array of 4 time objects:

    Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};

    for (int i = 0; i < 4; ++i)
       pq.push(t[i]);

    while (! pq.empty()) {
       Time t2 = pq.top();
       cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
       setw(3) << t2.s << endl;
       pq.pop();
    }

    return 0;
}

The program prints the times from latest to earliest:

5  16  13
5  14  20
3   2  40
3   2  26

If we wanted earliest times to have the highest priority, we would redefine CompareTime like this:

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
    {
       if (t2.h < t1.h) return true;
       if (t2.h == t1.h && t2.m < t1.m) return true;
       if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
       return false;
    }
};

Variable interpolation in the shell

In Bash:

tail -1 ${filepath}_newstap.sh

How to get query parameters from URL in Angular 5?

Angular Router provides method parseUrl(url: string) that parses url into UrlTree. One of the properties of UrlTree are queryParams. So you can do sth like:

this.router.parseUrl(this.router.url).queryParams[key] || '';

Pass all variables from one shell script to another?

You have basically two options:

  1. Make the variable an environment variable (export TESTVARIABLE) before executing the 2nd script.
  2. Source the 2nd script, i.e. . test2.sh and it will run in the same shell. This would let you share more complex variables like arrays easily, but also means that the other script could modify variables in the source shell.

UPDATE:

To use export to set an environment variable, you can either use an existing variable:

A=10
# ...
export A

This ought to work in both bash and sh. bash also allows it to be combined like so:

export A=10

This also works in my sh (which happens to be bash, you can use echo $SHELL to check). But I don't believe that that's guaranteed to work in all sh, so best to play it safe and separate them.

Any variable you export in this way will be visible in scripts you execute, for example:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

The fact that these are both shell scripts is also just incidental. Environment variables can be passed to any process you execute, for example if we used python instead it might look like:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.py

b.py:

#!/usr/bin/python

import os

print 'The message is:', os.environ['MESSAGE']

Sourcing:

Instead we could source like this:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

This more or less "imports" the contents of b.sh directly and executes it in the same shell. Notice that we didn't have to export the variable to access it. This implicitly shares all the variables you have, as well as allows the other script to add/delete/modify variables in the shell. Of course, in this model both your scripts should be the same language (sh or bash). To give an example how we could pass messages back and forth:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

echo "[A] The message is: $MESSAGE"

b.sh:

#!/bin/sh

echo "[B] The message is: $MESSAGE"

MESSAGE="goodbye"

Then:

$ ./a.sh
[B] The message is: hello
[A] The message is: goodbye

This works equally well in bash. It also makes it easy to share more complex data which you could not express as an environment variable (at least without some heavy lifting on your part), like arrays or associative arrays.

Sublime Text 3, convert spaces to tabs

Here is how you to do it automatically on save: https://coderwall.com/p/zvyg7a/convert-tabs-to-spaces-on-file-save

Unfortunately the package is not working when you install it from the Package Manager.

Conversion of Char to Binary in C

We show up two functions that prints a SINGLE character to binary.

void printbinchar(char character)
{
    char output[9];
    itoa(character, output, 2);
    printf("%s\n", output);
}

printbinchar(10) will write into the console

    1010

itoa is a library function that converts a single integer value to a string with the specified base. For example... itoa(1341, output, 10) will write in output string "1341". And of course itoa(9, output, 2) will write in the output string "1001".

The next function will print into the standard output the full binary representation of a character, that is, it will print all 8 bits, also if the higher bits are zero.

void printbincharpad(char c)
{
    for (int i = 7; i >= 0; --i)
    {
        putchar( (c & (1 << i)) ? '1' : '0' );
    }
    putchar('\n');
}

printbincharpad(10) will write into the console

    00001010

Now i present a function that prints out an entire string (without last null character).

void printstringasbinary(char* s)
{
    // A small 9 characters buffer we use to perform the conversion
    char output[9];

    // Until the first character pointed by s is not a null character
    // that indicates end of string...
    while (*s)
    {
        // Convert the first character of the string to binary using itoa.
        // Characters in c are just 8 bit integers, at least, in noawdays computers.
        itoa(*s, output, 2);

        // print out our string and let's write a new line.
        puts(output);

        // we advance our string by one character,
        // If our original string was "ABC" now we are pointing at "BC".
        ++s;
    }
}

Consider however that itoa don't adds padding zeroes, so printstringasbinary("AB1") will print something like:

1000001
1000010
110001

Customizing the template within a Directive

Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.

Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.

The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:

    angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        template: function(element, attrs) {
           var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
             return htmlText;
        }
        compile: function(element, attrs)
        {
           //do whatever else is necessary
        }
    }
})

Swap DIV position with CSS only

In some cases you can just use the flex-box property order.

Very simple:

.flex-item {
    order: 2;
}

See: https://css-tricks.com/almanac/properties/o/order/

how to get the 30 days before date from Todays Date

SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE());

Example.

SELECT `name`, `phone`, `product` FROM `tbmMember` WHERE `dateofServicw` < (Day,-30,GETDATE()); 

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

change <audio> src with javascript

Try this:

Replace:

audio.load();

with:

audio.play();

What is the fastest way to transpose a matrix in C++?

I think that most fast way should not taking higher than O(n^2) also in this way you can use just O(1) space :
the way to do that is to swap in pairs because when you transpose a matrix then what you do is: M[i][j]=M[j][i] , so store M[i][j] in temp, then M[i][j]=M[j][i],and the last step : M[j][i]=temp. this could be done by one pass so it should take O(n^2)

Check time difference in Javascript

I would use just getTime(); and for example Date.now() to return difference in milliseconds:

 //specified date:

var oneDate = new Date("November 02, 2017 06:00:00");

//number of milliseconds since midnight Jan 1 1970 till specified date

var oneDateMiliseconds = oneDate.getTime();

////number of milliseconds since midnight Jan 1 1970 till now

var currentMiliseconds = Date.now(); 

//return time difference in miliseconds

alert(currentMiliseconds-oneDateMiliseconds);

How can I remove the search bar and footer added by the jQuery DataTables plugin?

<script>
$(document).ready(function() {
    $('#nametable').DataTable({
        "bPaginate": false,
        "bFilter": false,
        "bInfo": false
    });
});
</script>

in your datatable constructor

https://datatables.net/forums/discussion/20006/how-to-remove-cross-icon-in-search-box

Rounding integer division (instead of truncating)

The standard idiom for integer rounding up is:

int a = (59 + (4 - 1)) / 4;

You add the divisor minus one to the dividend.

Should I use SVN or Git?

The funny thing is: I host projects in Subversion Repos, but access them via the Git Clone command.

Please read Develop with Git on a Google Code Project

Although Google Code natively speaks Subversion, you can easily use Git during development. Searching for "git svn" suggests this practice is widespread, and we too encourage you to experiment with it.

Using Git on a Svn Repository gives me benefits:

  1. I can work distributed on several machines, commiting and pulling from and to them
  2. I have a central backup/public svn repository for others to check out
  3. And they are free to use Git for their own

List append() in for loop

You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = []
for i in range(5):    
    a.append(i)
print(a)

is all you need. This works because lists are mutable.

Also see the docs on data structures.

When to use a linked list over an array/array list?

Arrays have O(1) random access, but are really expensive to add stuff onto or remove stuff from.

Linked lists are really cheap to add or remove items anywhere and to iterate, but random access is O(n).

Refreshing Web Page By WebDriver When Waiting For Specific Condition

There is also a case when you want to refresh only specific iframe on page and not the full page.

You do is as follows:

public void refreshIFrameByJavaScriptExecutor(String iFrameId){
        String script= "document.getElementById('" + iFrameId+ "').src = " + "document.getElementById('" + iFrameId+ "').src";
       ((IJavaScriptExecutor)WebDriver).ExecuteScript(script);
}

SQL Add foreign key to existing column

ALTER TABLE Faculty 
WITH CHECK ADD  CONSTRAINT FKFacultyBook
FOREIGN KEY FacId
REFERENCES Book Book_Id

ALTER TABLE Faculty 
WITH CHECK ADD  CONSTRAINT FKFacultyStudent 
FOREIGN KEY FacId
REFERENCES Student StuId

Pandas How to filter a Series

From pandas version 0.18+ filtering a series can also be done as below

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

pd.Series(test).where(lambda x : x!=1).dropna()

Checkout: http://pandas.pydata.org/pandas-docs/version/0.18.1/whatsnew.html#method-chaininng-improvements

When should we call System.exit in Java

In that case, it's not needed. No extra threads will have been started up, you're not changing the exit code (which defaults to 0) - basically it's pointless.

When the docs say the method never returns normally, it means the subsequent line of code is effectively unreachable, even though the compiler doesn't know that:

System.exit(0);
System.out.println("This line will never be reached");

Either an exception will be thrown, or the VM will terminate before returning. It will never "just return".

It's very rare to be worth calling System.exit() IME. It can make sense if you're writing a command line tool, and you want to indicate an error via the exit code rather than just throwing an exception... but I can't remember the last time I used it in normal production code.

manage.py runserver

in flask using flask.ext.script, you can do it like this:

python manage.py runserver -h 127.0.0.1 -p 8000

XAMPP Start automatically on Windows 7 startup

In addition to MR Chandru"s answer above, do these steps after configuring XAMPP:

  • open the directory where XAMPP is installed. By default it's installed at C:\xampp
  • Create Shortcut to the file xampp-control.exe, the XAMPP Control Panel
  • Paste it in

C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

or

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

The XAMPP Control Panel should now auto-start whenever you reboot Windows.

Check if record exists from controller in Rails

with 'exists?':

Business.exists? user_id: current_user.id #=> 1 or nil

with 'any?':

Business.where(:user_id => current_user.id).any? #=> true or false

If you use something with .where, be sure to avoid trouble with scopes and better use .unscoped

Business.unscoped.where(:user_id => current_user.id).any?

Double border with different color

I use outline a css 2 property that simply works. Check this out, is simple and even easy to animate:

_x000D_
_x000D_
.double-border {_x000D_
  display: block;_x000D_
  clear: both;_x000D_
  background: red;_x000D_
  border: 5px solid yellow;_x000D_
  outline: 5px solid blue;_x000D_
  transition: 0.7s all ease-in;_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
}_x000D_
.double-border:hover {_x000D_
  background: yellow;_x000D_
  outline-color: red;_x000D_
  border-color: blue;_x000D_
}
_x000D_
<div class="double-border"></div>
_x000D_
_x000D_
_x000D_

How to get the filename without the extension from a path in Python?

import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]

Zip lists in Python

In Python 2.7 this might have worked fine:

>>> a = b = c = range(20)
>>> zip(a, b, c)

But in Python 3.4 it should be (otherwise, the result will be something like <zip object at 0x00000256124E7DC8>):

>>> a = b = c = range(20)
>>> list(zip(a, b, c))

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

Running

set terminal pngcairo dashed
set output 'test.png'
test
set output

gives:

enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
test
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2
    

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
    
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
    
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

How to set a DateTime variable in SQL Server 2008?

You need to enclose the date time value in quotes:

DECLARE @Test AS DATETIME 

SET @Test = '2011-02-15'

PRINT @Test

Why does HTML think “chucknorris” is a color?

It’s a holdover from the Netscape days:

Missing digits are treated as 0[...]. An incorrect digit is simply interpreted as 0. For example the values #F0F0F0, F0F0F0, F0F0F, #FxFxFx and FxFxFx are all the same.

It is from the blog post A little rant about Microsoft Internet Explorer's color parsing which covers it in great detail, including varying lengths of color values, etc.

If we apply the rules in turn from the blog post, we get the following:

  1. Replace all nonvalid hexadecimal characters with 0’s:

    chucknorris becomes c00c0000000
    
  2. Pad out to the next total number of characters divisible by 3 (11 ? 12):

    c00c 0000 0000
    
  3. Split into three equal groups, with each component representing the corresponding colour component of an RGB colour:

    RGB (c00c, 0000, 0000)
    
  4. Truncate each of the arguments from the right down to two characters.

Which, finally, gives the following result:

RGB (c0, 00, 00) = #C00000 or RGB(192, 0, 0)

Here’s an example demonstrating the bgcolor attribute in action, to produce this “amazing” colour swatch:

_x000D_
_x000D_
<table>
  <tr>
    <td bgcolor="chucknorris" cellpadding="8" width="100" align="center">chuck norris</td>
    <td bgcolor="mrt"         cellpadding="8" width="100" align="center" style="color:#ffffff">Mr T</td>
    <td bgcolor="ninjaturtle" cellpadding="8" width="100" align="center" style="color:#ffffff">ninjaturtle</td>
  </tr>
  <tr>
    <td bgcolor="sick"  cellpadding="8" width="100" align="center">sick</td>
    <td bgcolor="crap"  cellpadding="8" width="100" align="center">crap</td>
    <td bgcolor="grass" cellpadding="8" width="100" align="center">grass</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

This also answers the other part of the question: Why does bgcolor="chucknorr" produce a yellow colour? Well, if we apply the rules, the string is:

c00c00000 => c00 c00 000 => c0 c0 00 [RGB(192, 192, 0)]

Which gives a light yellow gold colour. As the string starts off as 9 characters, we keep the second ‘C’ this time around, hence it ends up in the final colour value.

I originally encountered this when someone pointed out that you could do color="crap" and, well, it comes out brown.

Format a Go string without printing?

I've created go project for string formatting from template (it allow to format strings in C# or Python style, just first version for very simple cases), you could find it here https://github.com/Wissance/stringFormatter

it works in following manner:


func TestStrFormat(t *testing.T) {
    strFormatResult, err := Format("Hello i am {0}, my age is {1} and i am waiting for {2}, because i am {0}!",
                              "Michael Ushakov (Evillord666)", "34", "\"Great Success\"")
    assert.Nil(t, err)
    assert.Equal(t, "Hello i am Michael Ushakov (Evillord666), my age is 34 and i am waiting for \"Great Success\", because i am Michael Ushakov (Evillord666)!", strFormatResult)

    strFormatResult, err = Format("We are wondering if these values would be replaced : {5}, {4}, {0}", "one", "two", "three")
    assert.Nil(t, err)
    assert.Equal(t, "We are wondering if these values would be replaced : {5}, {4}, one", strFormatResult)

    strFormatResult, err = Format("No args ... : {0}, {1}, {2}")
    assert.Nil(t, err)
    assert.Equal(t, "No args ... : {0}, {1}, {2}", strFormatResult)
}

func TestStrFormatComplex(t *testing.T) {
    strFormatResult, err := FormatComplex("Hello {user} what are you doing here {app} ?", map[string]string{"user":"vpupkin", "app":"mn_console"})
    assert.Nil(t, err)
    assert.Equal(t, "Hello vpupkin what are you doing here mn_console ?", strFormatResult)
}

Cannot install packages using node package manager in Ubuntu

Your System is not able to detect the path node js binary.

1.which node

2.Then soft link node to nodejs

ln -s [the path of nodejs] /usr/bin/node 

I am assuming /usr/bin is in your execution path. Then you can test by typing node or npm into your command line, and everything should work now.

How do I restore a dump file from mysqldump?

How to Restore MySQL Database with MySQLWorkbench

You can run the drop and create commands in a query tab.

Drop the Schema if it Currently Exists

DROP DATABASE `your_db_name`;

Create a New Schema

CREATE SCHEMA `your_db_name`;

Open Your Dump File

MySQLWorkbench open sql file

  1. Click the Open an SQL script in a new query tab icon and choose your db dump file.
  2. Then Click Run SQL Script...
  3. It will then let you preview the first lines of the SQL dump script.
  4. You will then choose the Default Schema Name
  5. Next choose the Default Character Set utf8 is normally a safe bet, but you may be able to discern it from looking at the preview lines for something like character_set.
  6. Click Run
  7. Be patient for large DB restore scripts and watch as your drive space melts away!

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

ORA-12154: TNS:could not resolve the connect identifier specified?

In case the TNS is not defined you can also try this one:

If you are using C#.net 2010 or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:

static string constr = @"Data Source=(DESCRIPTION=
    (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
    (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
    User Id=system ;Password=yourpasswrd"; 

After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified then first you have to do restart your system and run your project.

And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:

Oracle Data Provider for .NET 2.0

Oracle Providers for ASP.NET

Oracle Developer Tools for Visual Studio

Oracle Instant Client 

And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......

Replacing Numpy elements if condition is met

>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
       [3, 0, 1, 2],
       [2, 0, 1, 1],
       [4, 0, 2, 3],
       [0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False,  True,  True,  True],
       [False,  True,  True,  True],
       [ True,  True,  True,  True],
       [False,  True,  True, False],
       [ True,  True,  True,  True]], dtype=bool)
>>> 
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 1, 1, 0],
       [1, 1, 1, 1]])

You can shorten this with:

>>> c = (a < 3).astype(int)

create a white rgba / CSS3

For completely transparent color, use:

rbga(255,255,255,0)

A little more visible:

rbga(255,255,255,.3)

How to add a default "Select" option to this ASP.NET DropDownList control?

Although it is quite an old question, another approach is to change AppendDataBoundItems property. So the code will be:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                  OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
                  AppendDataBoundItems="True">
     <asp:ListItem Selected="True" Value="0" Text="Select"></asp:ListItem>
</asp:DropDownList>

No server in windows>preferences

In Eclipse Kepler,

  1. go to Help, select ‘Install New Software’
  2. Choose “Kepler- http://download.eclipse.org/releases/kepler” site or add it in if it’s missing.
  3. Expand “Web, XML, and Java EE Development” section Check JST Server Adapters and JST Server Adapters Extensions and install it

After Eclipse restart, go to Window / Preferences / Server / Runtime Environments

Auto-click button element on page load using jQuery

Use the following code

$("#modal").trigger('click');

C# Collection was modified; enumeration operation may not execute

Any collection that you iterate over with foreach may not be modified during iteration.

So while you're running a foreach over rankings, you cannot modify its elements, add new ones or delete any.

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post but as you said "why is it not using the correct certificate" I would like to offer an way to find out which SSL certificate is used for SMTP (see here) which required openssl:

openssl s_client -connect exchange01.int.contoso.com:25 -starttls smtp

This will outline the used SSL certificate for the SMTP service. Based on what you see here you can replace the wrong certificate (like you already did) with a correct one (or trust the certificate manually).

How to bind 'touchstart' and 'click' events but not respond to both?

Well... All of these are super complicated.

If you have modernizr, it's a no-brainer.

ev = Modernizr.touch ? 'touchstart' : 'click';

$('#menu').on(ev, '[href="#open-menu"]', function(){
  //winning
});

Export HTML table to pdf using jspdf

Here is working example:

in head

<script type="text/javascript" src="jspdf.debug.js"></script>

script:

<script type="text/javascript">
        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            // source can be HTML-formatted string, or a reference
            // to an actual DOM element from which the text will be scraped.
            source = $('#customers')[0];

            // we support special element handlers. Register them with jQuery-style 
            // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
            // There is no support for any other type of selectors 
            // (class, of compound) at this time.
            specialElementHandlers = {
                // element with id of "bypass" - jQuery style selector
                '#bypassme': function(element, renderer) {
                    // true = "handled elsewhere, bypass text extraction"
                    return true
                }
            };
            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            };
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
            pdf.fromHTML(
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
                    margins.top, {// y coord
                        'width': margins.width, // max width of content on PDF
                        'elementHandlers': specialElementHandlers
                    },
            function(dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }
            , margins);
        }
    </script>

and table:

<div id="customers">
        <table id="tab_customers" class="table table-striped" >
            <colgroup>
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <col width="20%">
            </colgroup>
            <thead>         
                <tr class='warning'>
                    <th>Country</th>
                    <th>Population</th>
                    <th>Date</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Chinna</td>
                    <td>1,363,480,000</td>
                    <td>March 24, 2014</td>
                    <td>19.1</td>
                </tr>
                <tr>
                    <td>India</td>
                    <td>1,241,900,000</td>
                    <td>March 24, 2014</td>
                    <td>17.4</td>
                </tr>
                <tr>
                    <td>United States</td>
                    <td>317,746,000</td>
                    <td>March 24, 2014</td>
                    <td>4.44</td>
                </tr>
                <tr>
                    <td>Indonesia</td>
                    <td>249,866,000</td>
                    <td>July 1, 2013</td>
                    <td>3.49</td>
                </tr>
                <tr>
                    <td>Brazil</td>
                    <td>201,032,714</td>
                    <td>July 1, 2013</td>
                    <td>2.81</td>
                </tr>
            </tbody>
        </table> 
    </div>

and button to run:

<button onclick="javascript:demoFromHTML()">PDF</button>

and working example online:

tabel to pdf jspdf

or try this: HTML Table Export

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

./xx.py: line 1: import: command not found

Are you using a UNIX based OS such as Linux? If so, add a shebang line to the very top of your script:

#!/usr/bin/python

Underneath which you would have the rest of the code (xx.py in your case) that you already have. Then run that same command at the terminal:

$ python xx.py

This should then work fine, as it is now interpreting this as Python code. However when running from the terminal this does not matter as python tells how to interpret it here. What it does allow you to do is execute it outside the terminal, i.e. executing it from a file browser.

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

I think , your app installed by other account.( multiple account mode feature ) You can uninstall app in Setting>Apps>"app name"> Uninstall

Get skin path in Magento?

First of all it is not recommended to have php files with functions in design folder. You should create a new module or extend (copy from core to local a helper and add function onto that class) and do not change files from app/code/core.

To answer to your question you can use:

require(Mage::getBaseDir('design').'/frontend/default/mytheme/myfunc.php');

Best practice (as a start) will be to create in /app/code/local/Mage/Core/Helper/Extra.php a php file:

<?php
class Mage_Core_Helper_Extra extends Mage_Core_Helper_Abstract
{

    public function getSomething()
    {
        return 'Someting';
    }

}

And to use it in phtml files use:

$this->helper('core/extra')->getSomething();

Or in all the places:

Mage::helper('core/extra')->getSomething();

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

To check if variable is null or empty use this:

IF LEN(ISNULL(@var, '')) = 0
    -- Is empty or NULL
ELSE
    -- Is not empty and is not NULL

How can I add a .npmrc file?

This issue is because of you having some local or private packages. For accessing those packages you have to create .npmrc file for this issue. Just refer the following link for your solution. https://nodesource.com/blog/configuring-your-npmrc-for-an-optimal-node-js-environment

How do I wait until Task is finished in C#?

I'm an async novice, so I can't tell you definitively what is happening here. I suspect that there's a mismatch in the method execution expectations, even though you are using tasks internally in the methods. I think you'd get the results you are expecting if you changed Print to return a Task<string>:

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    Task<string> result;
    responseTask.ContinueWith(x => result = Print(x));
    result.Wait();
    responseTask.Wait(); // There's likely a better way to wait for both tasks without doing it in this awkward, consecutive way.
    return result.Result;
}

private static Task<string> Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    return task;
}

MySQL Install: ERROR: Failed to build gem native extension

In order to resolve

Gem::Ext::BuildError: ERROR: Failed to build gem native extension error for mysql2,

I think libmysql-ruby got changed with ruby-mysql

Simply try with following commands,

sudo apt-get install ruby-mysql

& then

sudo apt-get install libmysqlclient-dev

How can I count the number of elements with same class?

With jQuery you can use

$('#main-div .specific-class').length

otherwise in VanillaJS (from IE8 included) you may use

document.querySelectorAll('#main-div .specific-class').length;

How to execute a shell script in PHP?

Several possibilities:

  • You have safe mode enabled. That way, only exec() is working, and then only on executables in safe_mode_exec_dir
  • exec and shell_exec are disabled in php.ini
  • The path to the executable is wrong. If the script is in the same directory as the php file, try exec(dirname(__FILE__) . '/myscript.sh');

MySQL: How to reset or change the MySQL root password?

I had to go this route on Ubuntu 16.04.1 LTS. It is somewhat of a mix of some of the other answers above - but none of them helped. I spent an hour or more trying all other suggestions from MySql website to everything on SO, I finally got it working with:

Note: while it showed Enter password for user root, I didnt have the original password so I just entered the same password to be used as the new password.

Note: there was no /var/log/mysqld.log only /var/log/mysql/error.log

Also note this did not work for me:
sudo dpkg-reconfigure mysql-server-5.7

Nor did:
sudo dpkg-reconfigure --force mysql-server-5.5

Make MySQL service directory.
sudo mkdir /var/run/mysqld

Give MySQL user permission to write to the service directory.
sudo chown mysql: /var/run/mysqld

Then:

  1. kill the current mysqld pid
  2. run mysqld with sudo /usr/sbin/mysqld &
  3. run /usr/bin/mysql_secure_installation

    Output from mysql_secure_installation

    root@myServer:~# /usr/bin/mysql_secure_installation

    Securing the MySQL server deployment.

    Enter password for user root:

    VALIDATE PASSWORD PLUGIN can be used to test passwords and improve security. It checks the strength of password and allows the users to set only those passwords which are secure enough. Would you like to setup VALIDATE PASSWORD plugin?

    Press y|Y for Yes, any other key for No: no Using existing password for root. Change the password for root ? ((Press y|Y for Yes, any other key for No) : y

    New password:

    Re-enter new password: By default, a MySQL installation has an anonymous user, allowing anyone to log into MySQL without having to have a user account created for them. This is intended only for testing, and to make the installation go a bit smoother. You should remove them before moving into a production environment.

    Remove anonymous users? (Press y|Y for Yes, any other key for No) : y Success.

    Normally, root should only be allowed to connect from 'localhost'. This ensures that someone cannot guess at the root password from the network.

    Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y Success.

    By default, MySQL comes with a database named 'test' that anyone can access. This is also intended only for testing, and should be removed before moving into a production environment.

    Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y

    • Dropping test database... Success.

    • Removing privileges on test database... Success.

    Reloading the privilege tables will ensure that all changes made so far will take effect immediately.

    Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y Success.

    All done!

How to align form at the center of the page in html/css

Or you can just use the <center></center> tags.

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

Python loop for inside lambda

If you are like me just want to print a sequence within a lambda, without get the return value (list of None).

x = range(3)
from __future__ import print_function           # if not python 3
pra = lambda seq=x: map(print,seq) and None     # pra for 'print all'
pra()
pra('abc')

java.lang.RuntimeException: Uncompilable source code - what can cause this?

I guess you are using an IDE (like Netbeans) which allows you to run the code even if certain classes are not compilable. During the application's runtime, if you access this class it would lead to this exception.

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

In Swift how to call method with parameters on GCD main thread?

Swift 3+ & Swift 4 version:

DispatchQueue.main.async {
    print("Hello")
}

Swift 3 and Xcode 9.2:

dispatch_async_on_main_queue {
    print("Hello")
}

Eclipse error: "Editor does not contain a main type"

private int user_movie_matrix[][];Th. should be `private int user_movie_matrix[][];.

private int user_movie_matrix[][]; should be private static int user_movie_matrix[][];

cfiltering(numberOfUsers, numberOfMovies); should be new cfiltering(numberOfUsers, numberOfMovies);

Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.

Query to search all packages for table and/or column

You can do this:

select *
from user_source
where upper(text) like upper('%SOMETEXT%');

Alternatively, SQL Developer has a built-in report to do this under:

View > Reports > Data Dictionary Reports > PLSQL > Search Source Code

The 11G docs for USER_SOURCE are here

How to connect to my http://localhost web server from Android Emulator

You can actually use localhost:8000 to connect to your machine's localhost by running below command each time when you run your emulator (tested on Mac only):

adb reverse tcp:8000 tcp:8000

Just put it to Android Studio terminal.

It basically sets up a reverse proxy in which a http server running on your phone accepts connections on a port and wires them to your computer or vice versa.

How disable / remove android activity label and label bar?

public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  

        //set up notitle 
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        //set up full screen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  

        setContentView(R.layout.main);  
} 

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

In my case I changed the owner of all the files and it worked.

sudo chown -R anuruddha *

Python: 'break' outside loop

Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.

What are you trying to do? Perhaps you should use sys.exit() or return instead?

PHP Curl UTF-8 Charset

First method (internal function)

The best way I have tried before is to use urlencode(). Keep in mind, don't use it for the whole url; instead, use it only for the needed parts. For example, a request that has two 'text-fa' and 'text-en' fields and they contain a Persian and an English text, respectively, you might only need to encode the Persian text, not the English one.

Second Method (using cURL function)

However, there are better ways if the range of characters have to be encoded is more limited. One of these ways is using CURLOPT_ENCODING, by passing it to curl_setopt():

curl_setopt($ch, CURLOPT_ENCODING, "");

Python SQLite: database is locked

The reason mine was showing the "Lock" message was actually due to me having opened an SQLite3 IDE on my mac and that was the reason it was locked. I assume I was playing around with the DB within the IDE and hadn't saved the changes and therefor a lock was placed.

Cut long story short, check that there are no unsaved changes on the db and also that it is not being used elsewhere.

jQuery to remove an option from drop down list, given option's text/value

Many people had difficulty in using this keyword when we have iteration of Drop-downs with same elements but different values or say as Multi line data in USER INTERFACE. : Here is the code snippet : $(this).find('option[value=yourvalue]');

Hope you got this.

How do I check if an integer is even or odd?

This is a follow up to the discussion with @RocketRoy regarding his answer, but it might be useful to anyone who wants to compare these results.

tl;dr From what I've seen, Roy's approach ((0xFFFFFFFF == (x | 0xFFFFFFFE)) is not completely optimized to x & 1 as the mod approach, but in practice running times should turn out equal in all cases.

So, first I compared the compiled output using Compiler Explorer:

Functions tested:

int isOdd_mod(unsigned x) {
    return (x % 2);
}

int isOdd_and(unsigned x) {
    return (x & 1);
}

int isOdd_or(unsigned x) {
    return (0xFFFFFFFF == (x | 0xFFFFFFFE));
}   

CLang 3.9.0 with -O3:

isOdd_mod(unsigned int):                          # @isOdd_mod(unsigned int)
        and     edi, 1
        mov     eax, edi
        ret

isOdd_and(unsigned int):                          # @isOdd_and(unsigned int)
        and     edi, 1
        mov     eax, edi
        ret

isOdd_or(unsigned int):                           # @isOdd_or(unsigned int)
        and     edi, 1
        mov     eax, edi
        ret

GCC 6.2 with -O3:

isOdd_mod(unsigned int):
        mov     eax, edi
        and     eax, 1
        ret

isOdd_and(unsigned int):
        mov     eax, edi
        and     eax, 1
        ret

isOdd_or(unsigned int):
        or      edi, -2
        xor     eax, eax
        cmp     edi, -1
        sete    al
        ret

Hats down to CLang, it realized that all three cases are functionally equal. However, Roy's approach isn't optimized in GCC, so YMMV.

It's similar with Visual Studio; inspecting the disassembly Release x64 (VS2015) for these three functions, I could see that the comparison part is equal for "mod" and "and" cases, and slightly larger for the Roy's "or" case:

// x % 2
test bl,1  
je (some address) 

// x & 1
test bl,1  
je (some address) 

// Roy's bitwise or
mov eax,ebx  
or eax,0FFFFFFFEh  
cmp eax,0FFFFFFFFh  
jne (some address)

However, after running an actual benchmark for comparing these three options (plain mod, bitwise or, bitwise and), results were completely equal (again, Visual Studio 2005 x86/x64, Release build, no debugger attached).

Release assembly uses the test instruction for and and mod cases, while Roy's case uses the cmp eax,0FFFFFFFFh approach, but it's heavily unrolled and optimized so there is no difference in practice.

My results after 20 runs (i7 3610QM, Windows 10 power plan set to High Performance):

[Test: Plain mod 2 ] AVERAGE TIME: 689.29 ms (Relative diff.: +0.000%)
[Test: Bitwise or  ] AVERAGE TIME: 689.63 ms (Relative diff.: +0.048%)
[Test: Bitwise and ] AVERAGE TIME: 687.80 ms (Relative diff.: -0.217%)

The difference between these options is less than 0.3%, so it's rather obvious the assembly is equal in all cases.

Here is the code if anyone wants to try, with a caveat that I only tested it on Windows (check the #if LINUX conditional for the get_time definition and implement it if needed, taken from this answer).

#include <stdio.h>

#if LINUX
#include <sys/time.h>
#include <sys/resource.h>
double get_time()
{
    struct timeval t;
    struct timezone tzp;
    gettimeofday(&t, &tzp);
    return t.tv_sec + t.tv_usec*1e-6;
}
#else
#include <windows.h>
double get_time()
{
    LARGE_INTEGER t, f;
    QueryPerformanceCounter(&t);
    QueryPerformanceFrequency(&f);
    return (double)t.QuadPart / (double)f.QuadPart * 1000.0;
}
#endif

#define NUM_ITERATIONS (1000 * 1000 * 1000)

// using a macro to avoid function call overhead
#define Benchmark(accumulator, name, operation) { \
    double startTime = get_time(); \
    double dummySum = 0.0, elapsed; \
    int x; \
    for (x = 0; x < NUM_ITERATIONS; x++) { \
        if (operation) dummySum += x; \
    } \
    elapsed = get_time() - startTime; \
    accumulator += elapsed; \
    if (dummySum > 2000) \
        printf("[Test: %-12s] %0.2f ms\r\n", name, elapsed); \
}

void DumpAverage(char *test, double totalTime, double reference)
{
    printf("[Test: %-12s] AVERAGE TIME: %0.2f ms (Relative diff.: %+6.3f%%)\r\n",
        test, totalTime, (totalTime - reference) / reference * 100.0);
}

int main(void)
{
    int repeats = 20;
    double runningTimes[3] = { 0 };
    int k;

    for (k = 0; k < repeats; k++) {
        printf("Run %d of %d...\r\n", k + 1, repeats);
        Benchmark(runningTimes[0], "Plain mod 2", (x % 2));
        Benchmark(runningTimes[1], "Bitwise or", (0xFFFFFFFF == (x | 0xFFFFFFFE)));
        Benchmark(runningTimes[2], "Bitwise and", (x & 1));
    }

    {
        double reference = runningTimes[0] / repeats;
        printf("\r\n");
        DumpAverage("Plain mod 2", runningTimes[0] / repeats, reference);
        DumpAverage("Bitwise or", runningTimes[1] / repeats, reference);
        DumpAverage("Bitwise and", runningTimes[2] / repeats, reference);
    }

    getchar();

    return 0;
}

Recover unsaved SQL query scripts

For SSMS 18, I found the files at:

C:\Users\YourUserName\Documents\Visual Studio 2017\Backup Files\Solution1

For SSMS 17, It was used to be at:

C:\Users\YourUserName\Documents\Visual Studio 2015\Backup Files\Solution1

PHP Call to undefined function

How to reproduce the error, and how to fix it:

  1. Put this code in a file called p.php:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    ?>
    
  2. Run it like this:

    php p.php
    
  3. We get error:

    PHP Fatal error:  Call to undefined function salt() in 
    /home/el/foo/p.php on line 6
    
  4. Solution: use $this->salt(); instead of salt();

    So do it like this instead:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            $this->salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    
    ?>
    

If someone could post a link to why $this has to be used before PHP functions within classes, yeah, that would be great.

Can I have multiple Xcode versions installed?

Yes, you can install multiple versions of Xcode. They will install into separate directories. I've found that the best practice is to install the version that came with your Mac first and then install downloaded versions, but it probably doesn't make a big difference. See http://developer.apple.com/documentation/Xcode/Conceptual/XcodeCoexistence/Contents/Resources/en.lproj/Details/Details.html this Apple Developer Connection page for lots of details. <- Page does not exist anymore!

Adding attribute in jQuery

Add attribute as:

$('#Selector_id').attr('disabled',true);

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

For me, it was because I had an empty line between my @Component decorator and my Component class. This caused the decorator not to get applied to the class.

How to call external JavaScript function in HTML

In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-

caller.html

<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">

external.js

function letMeCallYou()
{
    alert("Bazinga!!!  you called letMeCallYou")
}

Result : enter image description here

Reading a text file with SQL Server

if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.

Class method decorator with self arguments?

Yes. Instead of passing in the instance attribute at class definition time, check it at runtime:

def check_authorization(f):
    def wrapper(*args):
        print args[0].url
        return f(*args)
    return wrapper

class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization
    def get(self):
        print 'get'

>>> Client('http://www.google.com').get()
http://www.google.com
get

The decorator intercepts the method arguments; the first argument is the instance, so it reads the attribute off of that. You can pass in the attribute name as a string to the decorator and use getattr if you don't want to hardcode the attribute name:

def check_authorization(attribute):
    def _check_authorization(f):
        def wrapper(self, *args):
            print getattr(self, attribute)
            return f(self, *args)
        return wrapper
    return _check_authorization

How to do the Recursive SELECT query in MySQL?

If you want to be able to have a SELECT without problems of the parent id having to be lower than child id, a function could be used. It supports also multiple children (as a tree should do) and the tree can have multiple heads. It also ensure to break if a loop exists in the data.

I wanted to use dynamic SQL to be able to pass the table/columns names, but functions in MySQL don't support this.

DELIMITER $$

CREATE FUNCTION `isSubElement`(pParentId INT, pId INT) RETURNS int(11)
DETERMINISTIC    
READS SQL DATA
BEGIN
DECLARE isChild,curId,curParent,lastParent int;
SET isChild = 0;
SET curId = pId;
SET curParent = -1;
SET lastParent = -2;

WHILE lastParent <> curParent AND curParent <> 0 AND curId <> -1 AND curParent <> pId AND isChild = 0 DO
    SET lastParent = curParent;
    SELECT ParentId from `test` where id=curId limit 1 into curParent;

    IF curParent = pParentId THEN
        SET isChild = 1;
    END IF;
    SET curId = curParent;
END WHILE;

RETURN isChild;
END$$

Here, the table test has to be modified to the real table name and the columns (ParentId,Id) may have to be adjusted for your real names.

Usage :

SET @wantedSubTreeId = 3;
SELECT * FROM test WHERE isSubElement(@wantedSubTreeId,id) = 1 OR ID = @wantedSubTreeId;

Result :

3   7   k
5   3   d
9   3   f
1   5   a

SQL for test creation :

CREATE TABLE IF NOT EXISTS `test` (
  `Id` int(11) NOT NULL,
  `ParentId` int(11) DEFAULT NULL,
  `Name` varchar(300) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

insert into test (id, parentid, name) values(3,7,'k');
insert into test (id, parentid, name) values(5,3,'d');
insert into test (id, parentid, name) values(9,3,'f');
insert into test (id, parentid, name) values(1,5,'a');
insert into test (id, parentid, name) values(6,2,'o');
insert into test (id, parentid, name) values(2,8,'c');

EDIT : Here is a fiddle to test it yourself. It forced me to change the delimiter using the predefined one, but it works.

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

How to do if-else in Thymeleaf?

<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a> 
</span>
</span>
</div>

enter image description here

Sorting Characters Of A C++ String

std::sort(str.begin(), str.end());

See here

Align text in a table header

For me none of the above worked. I think it is because I have two levels of header and a fixed width on level 1. So I couldn't align the text inside the corresponding columns on level 2.

+---------------------------+
|           lvl 1           |
+---------------------------+
| lvl 2 col a | lvl 2 col b |
+---------------------------+

I had to use the combination of width:auto and text:align-center :

<th style="width:auto;text-align:center">lvl 2 col a</th>
<th style="width:auto;text-align:center">lvl 2 col b</th>

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Here is how to do a quick check to see if n.fn.init[0] is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout function like this:

function timeout(){ 

    ...your selector function that returns n.fn.init[0] goes here...

}

setTimeout(timeout, 5000)

This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.

This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.

The preferred ways to check if the DOM is loaded before executing your function are as follows:

1) Wrap your selector function in

$(document).ready(function(){  ... your selector function...  };

2) If that doesn't work, use DOMContentLoaded

3) Try window.onload, which waits for all the images to load first, so its least preferred

window.onload = function () {  ... your selector function...  }

4) If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This question discusses how to check when MathJax library loaded its DOM elements, if it is of any help.

5) Finally, you can stick with hard-coded setTimeout function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.

This list of fixes is probably far from perfect so everyone is welcome to edit it.

Get list of certificates from the certificate store in C#

Yes -- the X509Store.Certificates property returns a snapshot of the X.509 certificate store.

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

On https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest I found this snippet that uses internal js module:

async function sha256(message) {
    // encode as UTF-8
    const msgBuffer = new TextEncoder().encode(message);                    

    // hash the message
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

    // convert ArrayBuffer to Array
    const hashArray = Array.from(new Uint8Array(hashBuffer));

    // convert bytes to hex string                  
    const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
    return hashHex;
}

Note that crypto.subtle in only available on https or localhost - for example for your local development with python3 -m http.server you need to add this line to your /etc/hosts: 0.0.0.0 localhost

Reboot - and you can open localhost:8000 with working crypto.subtle.