Programs & Examples On #Server side scripting

Server-side scripting is a web server technology in which a user's request is verified by running a script directly on the web server to generate dynamic web pages. It is usually used to provide interactive web sites that interface to databases or other data stores. Popular Server Side Scripting languages are PHP, ASP, Java (JSP), Perl and Server-side JavaScript.

How to set text color in submit button?

<input type = "button" style ="background-color:green"/>

ReferenceError: Invalid left-hand side in assignment

The same happened for me with eslint module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression for await in second if statement.

if (condition_one) {
  let result = await myFunction()
}

if (condition_two) {
  let result = await myFunction() // eslint parsing error
}

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.

if (condition_one) {
  let result = await myFunction();
}

if (condition_two) {
  let result = await myFunction();
}

Implementing two interfaces in a class with same method. Which interface method is overridden?

As far as the compiler is concerned, those two methods are identical. There will be one implementation of both.

This isn't a problem if the two methods are effectively identical, in that they should have the same implementation. If they are contractually different (as per the documentation for each interface), you'll be in trouble.

How to override !important?

I would like to add an answer to this that hasn't been mentioned, as I have tried all of the above to no avail. My specific situation is that I am using semantic-ui, which has built in !important attributes on elements (extremely annoying). I tried everything to override it, only in the end did one thing work (using jquery). It is as follows:

$('.active').css('cssText', 'border-radius: 0px !important');

Calculate RSA key fingerprint

Run the following command to retrieve the SHA256 fingerprint of your SSH key (-l means "list" instead of create a new key, -f means "filename"):

$ ssh-keygen -lf /path/to/ssh/key

So for example, on my machine the command I ran was (using RSA public key):

$ ssh-keygen -lf ~/.ssh/id_rsa.pub
2048 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff /Users/username/.ssh/id_rsa.pub (RSA)

To get the GitHub (MD5) fingerprint format with newer versions of ssh-keygen, run:

$ ssh-keygen -E md5 -lf <fileName>

Bonus information:

ssh-keygen -lf also works on known_hosts and authorized_keys files.

To find most public keys on Linux/Unix/OS X systems, run

$ find /etc/ssh /home/*/.ssh /Users/*/.ssh -name '*.pub' -o -name 'authorized_keys' -o -name 'known_hosts'

(If you want to see inside other users' homedirs, you'll have to be root or sudo.)

The ssh-add -l is very similar, but lists the fingerprints of keys added to your agent. (OS X users take note that magic passwordless SSH via Keychain is not the same as using ssh-agent.)

How to make Sonar ignore some classes for codeCoverage metric?

Sometimes, Clover is configured to provide code coverage reports for all non-test code. If you wish to override these preferences, you may use configuration elements to exclude and include source files from being instrumented:

<plugin>
    <groupId>com.atlassian.maven.plugins</groupId>
    <artifactId>maven-clover2-plugin</artifactId>
    <version>${clover-version}</version>
    <configuration> 
        <excludes> 
            <exclude>**/*Dull.java</exclude> 
        </excludes> 
    </configuration>
</plugin>

Also, you can include the following Sonar configuration:

<properties>
    <sonar.exclusions>
        **/domain/*.java,
        **/transfer/*.java
    </sonar.exclusions>
</properties> 

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

Eclipse plugin for generating a class diagram

Must it be an Eclipse plug-in? I use doxygen, just supply your code folder, it handles the rest.

AngularJS $location not changing the path

Instead of $location.path(...) to change or refresh the page, I used the service $window. In Angular this service is used as interface to the window object, and the window object contains a property location which enables you to handle operations related to the location or URL stuff.

For example, with window.location you can assign a new page, like this:

$window.location.assign('/');

Or refresh it, like this:

$window.location.reload();

It worked for me. It's a little bit different from you expect but works for the given goal.

How to send string from one activity to another?

Intents are intense.

Intents are useful for passing data around the android framework. You can communicate with your own Activities and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.

Swift addsubview and remove it

Tested this code using XCode 8 and Swift 3

To Add Custom View to SuperView use:

self.view.addSubview(myView)

To Remove Custom View from Superview use:

self.view.willRemoveSubview(myView)

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

I see in the documentation page an example like this:

<source src="foo.ogg" type="video/ogg; codecs=&quot;dirac, speex&quot;">

Maybe you should enclose the codec information with &quot; entities instead of actual quotes and the type attribute with quotes instead of apostrophes.

You can also try removing the codec info altogether.

how to set textbox value in jquery

Note that the .value attribute is a JavaScript feature. If you want to use jQuery, use:

$('#pid').val()

to get the value, and:

$('#pid').val('value')

to set it.

http://api.jquery.com/val/

Regarding your second issue, I have never tried automatically setting the HTML value using the load method. For sure, you can do something like this:

$('#subtotal').load( 'compz.php?prodid=' + x + '&qbuys=' + y, function(response){ $('#subtotal').val(response);
});

Note that the code above is untested.

http://api.jquery.com/load/

How do I push to GitHub under a different username?

If under Windows and user Git for Windows and the manager for managing the credentials (aka Git-Credential-Manager-for-Windows Link) the problem is that there is no easy way to switch amongst users when pushing to GitHub over https using OAuth tokens.

The reason is that the token is stored as:

  • Internet Address: git:https://github.com
  • Username: Personal Access Token
  • Password: OAuth_Token

Variations of the URL in Internet Address don't work, for example:

The solution: namespaces. This is found in the details for the configuration of the Git-Credential-Manager-for-Windows:

Quoting from it:

namespace

Sets the namespace for stored credentials.

By default the GCM uses the 'git' namespace for all stored credentials, setting this configuration value allows for control of the namespace used globally, or per host.

git config --global credential.namespace name

Now, store your credential in the Windows Credential Manager as:

  • Internet Address: git.username:https://github.com
  • Username: Personal Access Token
  • Password: OAuth_Token

Notice that we have changed: git -> git.username (where you change username to your actual username or for the sake of it, to whatever you may want as unique identifier)

Now, inside the repository where you want to use the specific entry, execute:

git config credential.namespace git.username

(Again ... replace username with your desired value)

Your .git/config will now contain:

[credential]
    namespace = git.username

Et voilá! The right credential will be pulled from the Windows Credential Store.

This, of course, doesn't change which user/e-mail is pushing. For that you have to configure the usual user.name and user.email

Parse date without timezone javascript

The Date object itself will contain timezone anyway, and the returned result is the effect of converting it to string in a default way. I.e. you cannot create a date object without timezone. But what you can do is mimic the behavior of Date object by creating your own one. This is, however, better to be handed over to libraries like moment.js.

How to use the priority queue STL for objects?

You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement

bool operator<(const Person& lhs, const Person& rhs); 

it should work without any further changes. The implementation could be

bool operator<(const Person& lhs, const Person& rhs)
{
  return lhs.age < rhs.age;
}

If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,

struct LessThanByAge
{
  bool operator()(const Person& lhs, const Person& rhs) const
  {
    return lhs.age < rhs.age;
  }
};

then instantiate the queue like this:

std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;

Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Here's how to fix this error when launching Eclipse:

Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.

  1. Go and install latest JDK

  2. Make sure you have installed 64 bit Eclipse

Apply .gitignore on an existing repository already tracking large number of files

I think this is an easy way for adding a .gitignore file to an existing repository.

Prerequisite:

You need a browser to access your github account.

Steps

  1. Create a new file in your required (existing) project and name it .gitignore. You will a get suggestive prompt for .gitignore templates as soon as you name the file as .gitignore. Either use these templates or use gitignore.io to generate the content of your gitignore file.
  2. Commit the changes.
  3. Now clone this repository.

Have fun!

How can I add an item to a ListBox in C# and WinForms?

ListBoxItem is a WPF class, NOT a WinForms class.

For WPF, use ListBoxItem.

For WinForms, the item is a Object type, so use one of these:
1. Provide your own ToString() method for the Object type.
2. Use databinding with DisplayMemeber and ValueMember (see Kelsey's answer)

Java regex capturing groups indexes

Parenthesis () are used to enable grouping of regex phrases.

The group(1) contains the string that is between parenthesis (.*) so .* in this case

And group(0) contains whole matched string.

If you would have more groups (read (...) ) it would be put into groups with next indexes (2, 3 and so on).

How to call Oracle MD5 hash function?

To calculate MD5 hash of CLOB content field with my desired encoding without implicitly recoding content to AL32UTF8, I've used this code:

create or replace function clob2blob(AClob CLOB) return BLOB is
  Result BLOB;
  o1 integer;
  o2 integer;
  c integer;
  w integer;
begin
  o1 := 1;
  o2 := 1;
  c := 0;
  w := 0;
  DBMS_LOB.CreateTemporary(Result, true);
  DBMS_LOB.ConvertToBlob(Result, AClob, length(AClob), o1, o2, 0, c, w);
  return(Result);
end clob2blob;
/

update my_table t set t.hash = (rawtohex(DBMS_CRYPTO.Hash(clob2blob(t.content),2)));

How can I get a file's size in C++?

#include <fstream>

std::ifstream::pos_type filesize(const char* filename)
{
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return in.tellg(); 
}

See http://www.cplusplus.com/doc/tutorial/files/ for more information on files in C++.

edit: this answer is not correct since tellg() does not necessarily return the right value. See http://stackoverflow.com/a/22986486/1835769

How to install php-curl in Ubuntu 16.04

This worked for me.

sudo apt-get install php-curl

What is the right way to POST multipart/form-data using curl?

This is what worked for me

curl --form file='@filename' URL

It seems when I gave this answer (4+ years ago), I didn't really understand the question, or how form fields worked. I was just answering based on what I had tried in a difference scenario, and it worked for me.

So firstly, the only mistake the OP made was in not using the @ symbol before the file name. Secondly, my answer which uses file=... only worked for me because the form field I was trying to do the upload for was called file. If your form field is called something else, use that name instead.

Explanation

From the curl manpages; under the description for the option --form it says:

This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.

Chances are that if you are trying to do a form upload, you will most likely want to use the @ prefix to upload the file rather than < which uploads the contents of the file.

Addendum

Now I must also add that one must be careful with using the < symbol because in most unix shells, < is the input redirection symbol [which coincidentally will also supply the contents of the given file to the command standard input of the program before <]. This means that if you do not properly escape that symbol or wrap it in quotes, you may find that your curl command does not behave the way you expect.

On that same note, I will also recommend quoting the @ symbol.


You may also be interested in this other question titled: application/x-www-form-urlencoded or multipart/form-data?

I say this because curl offers other ways of uploading a file, but they differ in the content-type set in the header. For example the --data option offers a similar mechanism for uploading files as data, but uses a different content-type for the upload.

Anyways that's all I wanted to say about this answer since it started to get more upvotes. I hope this helps erase any confusions such as the difference between this answer and the accepted answer. There is really none, except for this explanation.

Can't use WAMP , port 80 is used by IIS 7.5

goto services and stop the "World Wide Web Publishing Service" after restart the wamp server. after that start the "World Wide Web Publishing Service"

How to get the IP address of the server on which my C# application is running on?

Yet another way to get your public IP address is to use OpenDNS's resolve1.opendns.com server with myip.opendns.com as the request.

On the command line this is:

  nslookup myip.opendns.com resolver1.opendns.com

Or in C# using the DNSClient nuget:

  var lookup = new LookupClient(new IPAddress(new byte[] { 208, 67, 222, 222 }));
  var result = lookup.Query("myip.opendns.com", QueryType.ANY);

This is a bit cleaner than hitting http endpoints and parsing responses.

How to hide 'Back' button on navigation bar on iPhone?

navigationItem.leftBarButtonItem = nil
navigationItem.hidesBackButton = true

if you use this code block inside didLoad or loadView worked but not worked perfectly.If you look carefully you can see back button is hiding when your view load.Look's weird.

What is the perfect solution?

Add BarButtonItem component from componentView (Command + Shift + L) to your target viewControllers navigation bar.

Select BarButtonItem set Title = " " from right panel

enter image description here

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

How to mount a host directory in a Docker container

boot2docker together with VirtualBox Guest Additions
How to mount /Users into boot2docker

https://medium.com/boot2docker-lightweight-linux-for-docker/boot2docker-together-with-virtualbox-guest-additions-da1e3ab2465c

tl;dr Build your own custom boot2docker.iso with VirtualBox Guest Additions (see link) or download http://static.dockerfiles.io/boot2docker-v1.0.1-virtualbox-guest-additions-v4.3.12.iso and save it to ~/.boot2docker/boot2docker.iso.

Rename Files and Directories (Add Prefix)

Here is a simple script that you can use. I like using the non-standard module File::chdir to handle managing cd operations, so to use this script as-is you will need to install it (sudo cpan File::chdir).

#!/usr/bin/perl

use strict;
use warnings;

use File::Copy;
use File::chdir; # allows cd-ing by use of $CWD, much easier but needs CPAN module

die "Usage: $0 dir prefix" unless (@ARGV >= 2);
my ($dir, $pre) = @ARGV;

opendir(my $dir_handle, $dir) or die "Cannot open directory $dir";
my @files = readdir($dir_handle);
close($dir_handle);

$CWD = $dir; # cd to the directory, needs File::chdir

foreach my $file (@files) {
  next if ($file =~ /^\.+$/); # avoid folders . and ..
  next if ($0 =~ /$file/); # avoid moving this script if it is in the directory

  move($file, $pre . $file) or warn "Cannot rename file $file: $!";
}

How to set the allowed url length for a nginx request (error code: 414, uri too large)

For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;

You will need the sudo password.

sudo nano /etc/nginx/conf.d/uploads.conf

Replace contents with the following;

fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;

client_max_body_size 24M;
client_body_buffer_size 128k;

client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;

Force to open "Save As..." popup open at text link click for PDF in HTML

I just had a very similar issue with the added problem that I needed to create download links to files inside a ZIP file.

I first tried to create a temporary file, then provided a link to the temporary file, but I found that some browsers would just display the contents (a CSV Excel file) rather than offering to download. Eventually I found the solution by using a servlet. It works both on Tomcat and GlassFish, and I tried it on Internet Explorer 10 and Chrome.

The servlet takes as input a full path name to the ZIP file, and the name of the file inside the zip that should be downloaded.

Inside my JSP file I have a table displaying all the files inside the zip, with links that say: onclick='download?zip=<%=zip%>&csv=<%=csv%>'

The servlet code is in download.java:

package myServlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.zip.*;
import java.util.*;

// Extend HttpServlet class
public class download extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        PrintWriter out = response.getWriter(); // now we can write to the client

        String filename = request.getParameter("csv");
        String zipfile = request.getParameter("zip");

        String aLine = "";

        response.setContentType("application/x-download");
        response.setHeader( "Content-Disposition", "attachment; filename=" + filename); // Force 'save-as'
        ZipFile zip = new ZipFile(zipfile);
        for (Enumeration e = zip.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            if(entry.toString().equals(filename)) {
                InputStream is = zip.getInputStream(entry);
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 65536);
                while ((aLine = br.readLine()) != null) {
                    out.println(aLine);
                }
                is.close();
                break;
            }
        }
    }
}

To compile on Tomcat you need the classpath to include tomcat\lib\servlet-api.jar or on GlassFish: glassfish\lib\j2ee.jar

But either one will work on both. You also need to set your servlet in web.xml.

Remove Select arrow on IE

In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before css to match yours.

In case if it is IE10 then using below css3 it is possible

select::-ms-expand {
    display: none;
}

However if you're interested in jQuery plugin, try Chosen.js or you can create your own in js.

Animate text change in UILabel

This is a C# UIView extension method that's based on @SwiftArchitect's code. When auto layout is involved and controls need to move depending on the label's text, this calling code uses the Superview of the label as the transition view instead of the label itself. I added a lambda expression for the action to make it more encapsulated.

public static void FadeTransition( this UIView AView, double ADuration, Action AAction )
{
  CATransition transition = new CATransition();

  transition.Duration = ADuration;
  transition.TimingFunction = CAMediaTimingFunction.FromName( CAMediaTimingFunction.Linear );
  transition.Type = CATransition.TransitionFade;

  AView.Layer.AddAnimation( transition, transition.Type );
  AAction();
}

Calling code:

  labelSuperview.FadeTransition( 0.5d, () =>
  {
    if ( condition )
      label.Text = "Value 1";
    else
      label.Text = "Value 2";
  } );

How to get the text of the selected value of a dropdown list?

You can use option:selected to get the chosen option of the select element, then the text() method:

$("select option:selected").text();

Here's an example:

_x000D_
_x000D_
console.log($("select option:selected").text());
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<select>_x000D_
    <option value="1">Volvo</option>_x000D_
    <option value="2" selected="selected">Saab</option>_x000D_
    <option value="3">Mercedes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

C char array initialization

  1. These are equivalent

    char buf[10] = "";
    char buf[10] = {0};
    char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  2. These are equivalent

    char buf[10] = " ";
    char buf[10] = {' '};
    char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  3. These are equivalent

    char buf[10] = "a";
    char buf[10] = {'a'};
    char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

External resource not being loaded by AngularJs

I ran into the same problem using Videogular. I was getting the following when using ng-src:

Error: [$interpolate:interr] Can't interpolate: {{url}}
Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy

I fixed the problem by writing a basic directive:

angular.module('app').directive('dynamicUrl', function () {
return {
  restrict: 'A',
  link: function postLink(scope, element, attrs) {
    element.attr('src', scope.content.fullUrl);
  }
};
});

The html:

 <div videogular vg-width="200" vg-height="300" vg-theme="config.theme">
    <video class='videoPlayer' controls preload='none'>
          <source dynamic-url src='' type='{{ content.mimeType }}'>
    </video>
 </div>

Pandas percentage of total with groupby

df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999)
                         for _ in range(12)]})

grouped = df.groupby(['state', 'office_id'])
100*grouped.sum()/df[["state","sales"]].groupby('state').sum()

Returns:

sales
state   office_id   
AZ  2   54.587910
    4   33.009225
    6   12.402865
CA  1   32.046582
    3   44.937684
    5   23.015735
CO  1   21.099989
    3   31.848658
    5   47.051353
WA  2   43.882790
    4   10.265275
    6   45.851935

What is newline character -- '\n'

NewLine (\n) is 10 (0xA) and CarriageReturn (\r) is 13 (0xD).

Different operating systems picked different end of line representations for files. Windows uses CRLF (\r\n). Unix uses LF (\n). Older Mac OS versions use CR (\r), but OS X switched to the Unix character.

Here is a relatively useful FAQ.

How to inspect Javascript Objects

This is blatant rip-off of Christian's excellent answer. I've just made it a bit more readable:

/**
 * objectInspector digs through a Javascript object
 * to display all its properties
 *
 * @param object - a Javascript object to inspect
 * @param result - a string of properties with datatypes
 *
 * @return result - the concatenated description of all object properties
 */
function objectInspector(object, result) {
    if (typeof object != "object")
        return "Invalid object";
    if (typeof result == "undefined")
        result = '';

    if (result.length > 50)
        return "[RECURSION TOO DEEP. ABORTING.]";

    var rows = [];
    for (var property in object) {
        var datatype = typeof object[property];

        var tempDescription = result+'"'+property+'"';
        tempDescription += ' ('+datatype+') => ';
        if (datatype == "object")
            tempDescription += 'object: '+objectInspector(object[property],result+'  ');
        else
            tempDescription += object[property];

        rows.push(tempDescription);
    }//Close for

    return rows.join(result+"\n");
}//End objectInspector

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

Soft keyboard open and close listener in an activity in Android

You can handle keyboard visibility by overriding two methods in your Activity: onKeyUp() and onKeyDown() more information in this link: https://developer.android.com/training/keyboard-input/commands

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Umair R's answer is mostly the right move to solve the problem, as this error used to be caused by the missing links between opencv libs and the programme. so there is the need to specify the ld_libraty_path configuration. ps. the usual library path is suppose to be:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

I have tried this and it worked well.

Google maps Places API V3 autocomplete - select first option on enter

It seems there is a much better and clean solution: To use google.maps.places.SearchBox instead of google.maps.places.Autocomplete. A code is almost the same, just getting the first from multiple places. On pressing the Enter the the correct list is returned - so it runs out of the box and there is no need for hacks.

See the example HTML page:

http://rawgithub.com/klokan/8408394/raw/5ab795fb36c67ad73c215269f61c7648633ae53e/places-enter-first-item.html

The relevant code snippet is:

var searchBox = new google.maps.places.SearchBox(document.getElementById('searchinput'));

google.maps.event.addListener(searchBox, 'places_changed', function() {
  var place = searchBox.getPlaces()[0];

  if (!place.geometry) return;

  if (place.geometry.viewport) {
    map.fitBounds(place.geometry.viewport);
  } else {
    map.setCenter(place.geometry.location);
    map.setZoom(16);
  }
});

The complete source code of the example is at: https://gist.github.com/klokan/8408394

How can I rollback a git repository to a specific commit?

git reset --hard <old-commit-id>
git push -f <remote-name> <branch-name>

Note: As written in comments below, Using this is dangerous in a collaborative environment: you're rewriting history

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

I'd say

concat('This is line 1.', 0xd0a, 'This is line 2.')

or

concat(N'This is line 1.', 0xd000a, N'This is line 2.')

console.log timestamps in Chrome?

You can use dev tools profiler.

console.time('Timer name');
//do critical time stuff
console.timeEnd('Timer name');

"Timer name" must be the same. You can use multiple instances of timer with different names.

Android fade in and fade out with ImageView

I used used fadeIn animation to replace new image for old one

ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();

How to get subarray from array?

For a simple use of slice, use my extension to Array Class:

Array.prototype.subarray = function(start, end) {
    if (!end) { end = -1; } 
    return this.slice(start, this.length + 1 - (end * -1));
};

Then:

var bigArr = ["a", "b", "c", "fd", "ze"];

Test1:

bigArr.subarray(1, -1);

< ["b", "c", "fd", "ze"]

Test2:

bigArr.subarray(2, -2);

< ["c", "fd"]

Test3:

bigArr.subarray(2);

< ["c", "fd","ze"]

Might be easier for developers coming from another language (i.e. Groovy).

How do I create a new line in Javascript?

\n --> newline character is not working for inserting a new line.

    str="Hello!!";
    document.write(str);
    document.write("\n");
    document.write(str);

But if we use below code then it works fine and it gives new line.

    document.write(str);
    document.write("<br>");
    document.write(str);

Note:: I tried in Visual Studio Code.

Missing Microsoft RDLC Report Designer in Visual Studio

If you did a custom installation you need to add Microsoft Sql Server Data Tools. After that you can add Reportviwer to your webform.

Multi-character constant warnings

If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:

-Wno-multichar

I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.

Android/Eclipse: how can I add an image in the res/drawable folder?

Drop in the image in /res/drawable folder. Then in Eclipse Menu, do ->Project -> Clean. This will do a clean build if set to build automatically.

PowerShell To Set Folder Permissions

In case you had to deal with a lot of subfolders contatining subfolders and other recursive stuff. Small improvment of @Mike L'Angelo:

$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose

Verbosity is optional in the last line

How to specify the download location with wget?

Make sure you have the URL correct for whatever you are downloading. First of all, URLs with characters like ? and such cannot be parsed and resolved. This will confuse the cmd line and accept any characters that aren't resolved into the source URL name as the file name you are downloading into.

For example:

wget "sourceforge.net/projects/ebosse/files/latest/download?source=typ_redirect"

will download into a file named, ?source=typ_redirect.

As you can see, knowing a thing or two about URLs helps to understand wget.

I am booting from a hirens disk and only had Linux 2.6.1 as a resource (import os is unavailable). The correct syntax that solved my problem downloading an ISO onto the physical hard drive was:

wget "(source url)" -O (directory where HD was mounted)/isofile.iso" 

One could figure the correct URL by finding at what point wget downloads into a file named index.html (the default file), and has the correct size/other attributes of the file you need shown by the following command:

wget "(source url)"

Once that URL and source file is correct and it is downloading into index.html, you can stop the download (ctrl + z) and change the output file by using:

-O "<specified download directory>/filename.extension"

after the source url.

In my case this results in downloading an ISO and storing it as a binary file under isofile.iso, which hopefully mounts.

Find number of decimal places in decimal value regardless of culture

As a decimal extension method that takes into account:

  • Different cultures
  • Whole numbers
  • Negative numbers
  • Trailing set zeros on the decimal place (e.g. 1.2300M will return 2 not 4)
public static class DecimalExtensions
{
    public static int GetNumberDecimalPlaces(this decimal source)
    {
        var parts = source.ToString(CultureInfo.InvariantCulture).Split('.');

        if (parts.Length < 2)
            return 0;

        return parts[1].TrimEnd('0').Length;
    }
}

Ansible: Set variable to file content

You can use lookups in Ansible in order to get the contents of a file, e.g.

user_data: "{{ lookup('file', user_data_file) }}"

Caveat: This lookup will work with local files, not remote files.

Here's a complete example from the docs:

- hosts: all
  vars:
     contents: "{{ lookup('file', '/etc/foo.txt') }}"
  tasks:
     - debug: msg="the value of foo.txt is {{ contents }}"

How to do a redirect to another route with react-router?

Easiest solution for web!

Up to date 2020
confirmed working with:

"react-router-dom": "^5.1.2"
"react": "^16.10.2"

Use the useHistory() hook!

import React from 'react';
import { useHistory } from "react-router-dom";


export function HomeSection() {
  const history = useHistory();
  const goLogin = () => history.push('login');

  return (
    <Grid>
      <Row className="text-center">          
        <Col md={12} xs={12}>
          <div className="input-group">
            <span className="input-group-btn">
              <button onClick={goLogin} type="button" />
            </span>
          </div>
        </Col>
      </Row>
    </Grid>
  );
}

How can I detect the encoding/codepage of a text file

The StreamReader class's constructor takes a 'detect encoding' parameter.

How do I clone a generic List in Java?

Be very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original.

How to run Java program in command prompt

A very general command prompt how to for java is

javac mainjava.java
java mainjava

You'll very often see people doing

javac *.java
java mainjava

As for the subclass problem that's probably occurring because a path is missing from your class path, the -c flag I believe is used to set that.

Strip HTML from strings in Python

I haven't thought much about the cases it will miss, but you can do a simple regex:

re.sub('<[^<]+?>', '', text)

For those that don't understand regex, this searches for a string <...>, where the inner content is made of one or more (+) characters that isn't a <. The ? means that it will match the smallest string it can find. For example given <p>Hello</p>, it will match <'p> and </p> separately with the ?. Without it, it will match the entire string <..Hello..>.

If non-tag < appears in html (eg. 2 < 3), it should be written as an escape sequence &... anyway so the ^< may be unnecessary.

How do I enable php to work with postgresql?

I and many other shave spent way too long on this - this needs a massive improvement. After spending hours, I finally copied php_pgsql.dll from php's ext directory to Apache24's root directory (wherever you installed it) and finally Apache was able to get the php/pg modules and dlls loaded.

How do I make an HTML button not reload the page

In HTML:

<form onsubmit="return false">
</form>

in order to avoid refresh at all "buttons", even with onclick assigned.

SQL - HAVING vs. WHERE

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

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

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

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

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

how to initialize a char array?

memset(msg, 0, 65546)

E11000 duplicate key error index in mongodb mongoose

Please clear the collection or Delete the entire collection from MongoDB database and try again later.

Undefined reference to pthread_create in Linux

you need only Add "pthread" in proprieties=>C/C++ build=>GCC C++ Linker=>Libraries=> top part "Libraries(-l)". thats it

Invoke native date picker from web-app on iOS/Android

Give Mobiscroll a try. The scroller style date and time picker was especially created for interaction on touch devices. It is pretty flexible, and easily customizable. It comes with iOS/Android themes.

How to check if element has any children in Javascript?

<script type="text/javascript">

function uwtPBSTree_NodeChecked(treeId, nodeId, bChecked) 
{
    //debugger;
    var selectedNode = igtree_getNodeById(nodeId);
    var ParentNodes = selectedNode.getChildNodes();

    var length = ParentNodes.length;

    if (bChecked) 
    {
/*                if (length != 0) {
                    for (i = 0; i < length; i++) {
                        ParentNodes[i].setChecked(true);
                    }
    }*/
    }
    else 
    {
        if (length != 0) 
        {
            for (i = 0; i < length; i++) 
            {
                ParentNodes[i].setChecked(false);
            }
        }
    }
}
</script>

<ignav:UltraWebTree ID="uwtPBSTree" runat="server"..........>
<ClientSideEvents NodeChecked="uwtPBSTree_NodeChecked"></ClientSideEvents>
</ignav:UltraWebTree>

How to sort two lists (which reference each other) in the exact same way

One way is to track where each index goes to by sorting the identity [0,1,2,..n]

This works for any number of lists.

Then move each item to its position. Using splices is best.

list1 = [3,2,4,1, 1]
list2 = ['three', 'two', 'four', 'one', 'one2']

index = list(range(len(list1)))
print(index)
'[0, 1, 2, 3, 4]'

index.sort(key = list1.__getitem__)
print(index)
'[3, 4, 1, 0, 2]'

list1[:] = [list1[i] for i in index]
list2[:] = [list2[i] for i in index]

print(list1)
print(list2)
'[1, 1, 2, 3, 4]'
"['one', 'one2', 'two', 'three', 'four']"

Note we could have iterated the lists without even sorting them:

list1_iter = (list1[i] for i in index)

How to create a timer using tkinter?

Tkinter root windows have a method called after which can be used to schedule a function to be called after a given period of time. If that function itself calls after you've set up an automatically recurring event.

Here is a working example:

# for python 3.x use 'tkinter' rather than 'Tkinter'
import Tkinter as tk
import time

class App():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop()

    def update_clock(self):
        now = time.strftime("%H:%M:%S")
        self.label.configure(text=now)
        self.root.after(1000, self.update_clock)

app=App()

Bear in mind that after doesn't guarantee the function will run exactly on time. It only schedules the job to be run after a given amount of time. It the app is busy there may be a delay before it is called since Tkinter is single-threaded. The delay is typically measured in microseconds.

UTF-8 byte[] to String

Look at the constructor for String

String str = new String(bytes, StandardCharsets.UTF_8);

And if you're feeling lazy, you can use the Apache Commons IO library to convert the InputStream to a String directly:

String str = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

jQuery: selecting each td in a tr

expanding on the answer above the 'each' function will return you the table-cell html object. wrapping that in $() will then allow you to perform jquery actions on it.

$(this).find('td').each (function( column, td) {
  $(td).blah
});  

LINQ to read XML

Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:

//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ1
{
    static void Main( )
    {
        //Load xml
        XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path

        //Run query
        var lv1s = from lv1 in xdoc.Descendants("level1")
           select new 
           { 
               Header = lv1.Attribute("name").Value,
               Children = lv1.Descendants("level2")
            };

        StringBuilder result = new StringBuilder(); //had to add this to make the result work
        //Loop through results
        foreach (var lv1 in lv1s)
        {
            result.AppendLine("  " + lv1.Header);
            foreach(var lv2 in lv1.Children)
            result.AppendLine("    " + lv2.Attribute("name").Value);
        }
        Console.WriteLine(result.ToString()); //added this so you could see the output on the console
    }
}

And next:

//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ
{
static void Main( )
    {
        XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
        Console.WriteLine(GetOutline(0, rootElement));  
    }

static private string GetOutline(int indentLevel, XElement element)
    {
        StringBuilder result = new StringBuilder();
        if (element.Attribute("name") != null)
        {
            result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
        }
        foreach (XElement childElement in element.Elements())
        {
            result.Append(GetOutline(indentLevel + 1, childElement));
        }
        return result.ToString();
    }
}

These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.

EDIT: added @eglasius' example as well since it became useful to me:

//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ2
{
    static void Main( )
    {
        StringBuilder result = new StringBuilder(); //needed for result below
        XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
        var lv1s = xdoc.Root.Descendants("level1"); 
        var lvs = lv1s.SelectMany(l=>
             new string[]{ l.Attribute("name").Value }
             .Union(
                 l.Descendants("level2")
                 .Select(l2=>"   " + l2.Attribute("name").Value)
              )
            );
        foreach (var lv in lvs)
        {
           result.AppendLine(lv);
        }
        Console.WriteLine(result);//added this so you could see the result
    }
}

How do I get SUM function in MySQL to return '0' if no values are found?

Can't get exactly what you are asking but if you are using an aggregate SUM function which implies that you are grouping the table.

The query goes for MYSQL like this

Select IFNULL(SUM(COLUMN1),0) as total from mytable group by condition

Wait 5 seconds before executing next line

You have to put your code in the callback function you supply to setTimeout:

function stateChange(newState) {
    setTimeout(function () {
        if (newState == -1) {
            alert('VIDEO HAS STOPPED');
        }
    }, 5000);
}

Any other code will execute immediately.

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

How do shift operators work in Java?

Signed left shift Logically Simple if 1<<11 it will tends to 2048 and 2<<11 will give 4096

In java programming int a = 2 << 11;

// it will result in 4096

2<<11 = 2*(2^11) = 4096

matrix multiplication algorithm time complexity

The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).

There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.

See this wikipedia article on Matrix Multiplication for more information.

How to open adb and use it to send commands

The adb tool can be found in sdk/platform-tools/

If you don't see this directory in your SDK, launch the SDK Manager and install "Android SDK Platform-tools"

Also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

How to compile and run C files from within Notepad++ using NppExec plugin?

I personally use the following batch script that can be used on many types of files (C, makefile, Perl scripts, shell scripts, batch, ...).

How to use it:

  1. Install NppExec plugin
  2. Store this file in the Notepad++ user directory (%APPDATA%/Notepad++) under the name runNcompile.bat (but you can name it whatever you like).
  3. while checking the option "Follow $(CURRENT_DIRECTORY)" in NppExec menu
  4. Add a NppExec command "$(SYS.APPDATA)\Notepad++\runNcompile.bat" "$(FULL_CURRENT_PATH)" (optionally, you can put npp_save on the first line to save the file before running it)
  5. Assign a special key (I reassigned F12) to launch the script.

This page explains quite clearly the global flow: https://www.thecrazyprogrammer.com/2015/08/configure-notepad-to-run-c-cpp-and-java-programs.html

Hope it can help

  @echo off

REM ----------------------
REM ----- ARGUMENTS ------
REM ----------------------
set FPATH=%~1
set FILE=%~n1
set DIR=%~dp1
set EXTENSION=%~x1
REM ----------------------



REM ----------------------
REM ------- CONFIG -------
REM ----------------------
REM C Compiler (gcc.exe or cl.exe) + options + object extension
set CL_compilo=gcc.exe
set CFLAGS=-c "%FPATH%"
set OBJ_Ext=o
REM GNU make
set GNU_make=make.exe
REM ----------------------




IF /I "%FILE%"==Makefile GOTO _MAKEFILE
IF /I %EXTENSION%==.bat GOTO _BAT
IF /I %EXTENSION%==.sh GOTO _SH
IF /I %EXTENSION%==.pl GOTO _PL
IF /I %EXTENSION%==.tcl GOTO _TCL
IF /I %EXTENSION%==.c GOTO _C
IF /I %EXTENSION%==.mak GOTO _MAKEFILE
IF /I %EXTENSION%==.mk GOTO _MAKEFILE
IF /I %EXTENSION%==.html GOTO _HTML
echo Format of argument (%FPATH%) not supported!
GOTO END


REM Batch shell files (bat)
:_BAT
call "%FPATH%"
goto END


REM Linux shell scripts (sh)
:_SH
call sh.exe "%FPATH%"
goto END


REM Perl Script files (pl)
:_PL
call perl.exe "%FPATH%"
goto END


REM Tcl Script files (tcl)
:_TCL
call tclsh.exe "%FPATH%"
goto END


REM Compile C Source files (C)
:_C
REM MAKEFILES...
IF EXIST "%DIR%Makefile" ( cd "%DIR%" )
IF EXIST "%DIR%../Makefile" ( cd "%DIR%/.." )
IF EXIST "%DIR%../../Makefile" ( cd "%DIR%/../.." )
IF EXIST "Makefile" ( 
    call %GNU_make% all
    goto END
)
REM COMPIL...
echo -%CL_compilo% %CFLAGS%-
call %CL_compilo% %CFLAGS%
IF %ERRORLEVEL% EQU 0 (
    echo -%CL_compilo% -o"%DIR%%FILE%.exe" "%DIR%%FILE%.%OBJ_Ext%"-
    call %CL_compilo% -o"%DIR%%FILE%.exe" "%DIR%%FILE%.%OBJ_Ext%" 
)
IF %ERRORLEVEL% EQU 0 (del "%DIR%%FILE%.%OBJ_Ext%")
goto END


REM Open HTML files in web browser (html and htm)
:_HTML
start /max /wait %FPATH%
goto END

REM ... END ...
:END
echo.
IF /I "%2" == "-pause" pause

How do I get the color from a hexadecimal color code using .NET?

Assuming you mean the HTML type RGB codes (called Hex codes, such as #FFCC66), use the ColorTranslator class:

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");

If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:

Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or      = (Color) ColorConverter.ConvertFromString("#FFCC66") ;

Turning error reporting off php

Tried this yet?

error_reporting(0);
@ini_set('display_errors', 0);

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

If you are not using Maven, just drop the javax.servlet-api.jar in your project lib folder.

Excel: Creating a dropdown using a list in another sheet?

Yes it is. Use Data Validation from the Data panel. Select Allow: List and pick those cells on the other sheet as your source.

MySQL - sum column value(s) based on row from the same table

I think you're making this a bit more complicated than it needs to be.

SELECT
    ProductID,
    SUM(IF(PaymentMethod = 'Cash', Amount, 0)) AS 'Cash',
    -- snip
    SUM(Amount) AS Total
FROM
    Payments
WHERE
    SaleDate = '2012-02-10'
GROUP BY
    ProductID

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

parseDouble returns a primitive double containing the value of the string:

Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.

valueOf returns a Double instance, if already cached, you'll get the same cached instance.

Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

To avoid the overhead of creating a new Double object instance, you should normally use valueOf

Angularjs - simple form submit

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

Angularjs - Form Post Data Not Posted?

The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

Disallow Twitter Bootstrap modal window from closing

Yes, you can do it like this:

<div id="myModal"  tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel"
     aria-hidden="true"
     data-backdrop="static"  data-keyboard="false">

React Native Responsive Font Size

Why not using PixelRatio.getPixelSizeForLayoutSize(/* size in dp */);, it's just the same as pd units in Android.

How to get client IP address in Laravel 5+

If you call this function then you easily get the client's IP address. I have already used this in my existing project:

public function getUserIpAddr(){
       $ipaddress = '';
       if (isset($_SERVER['HTTP_CLIENT_IP']))
           $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
       else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
           $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
       else if(isset($_SERVER['HTTP_X_FORWARDED']))
           $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
       else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
           $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
       else if(isset($_SERVER['HTTP_FORWARDED']))
           $ipaddress = $_SERVER['HTTP_FORWARDED'];
       else if(isset($_SERVER['REMOTE_ADDR']))
           $ipaddress = $_SERVER['REMOTE_ADDR'];
       else
           $ipaddress = 'UNKNOWN';    
       return $ipaddress;
    }

How to get streaming url from online streaming radio station

When you go to a stream url, you get offered a file. feed this file to a parser to extract the contents out of it. the file is (usually) plain text and contains the url to play.

How to get datetime in JavaScript?

try this:

_x000D_
_x000D_
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours()+':'+today.getMinutes()+':'+today.getSeconds();
console.log(date + ' '+ time);
_x000D_
_x000D_
_x000D_

Bubble Sort Homework

def bubbleSort(alist):
if len(alist) <= 1:
    return alist
for i in range(0,len(alist)):
   print "i is :%d",i
   for j in range(0,i):
      print "j is:%d",j
      print "alist[i] is :%d, alist[j] is :%d"%(alist[i],alist[j])
      if alist[i] > alist[j]:
         alist[i],alist[j] = alist[j],alist[i]
return alist

alist = [54,26,93,17,77,31,44,55,20,-23,-34,16,11,11,11]

print bubbleSort(alist)

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

As of 2018-05 this is handled directly with decode, at least for Python 3.

I'm using the below snippet for invalid start byte and invalid continuation byte type errors. Adding errors='ignore' fixed it for me.

with open(out_file, 'rb') as f:
    for line in f:
        print(line.decode(errors='ignore'))

How do you reverse a string in place in JavaScript?

You can't because JS strings are immutable. Short non-in-place solution

[...str].reverse().join``

_x000D_
_x000D_
let str = "Hello World!";_x000D_
let r = [...str].reverse().join``;_x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

Windows Forms - Enter keypress activates submit button?

As previously stated, set your form's AcceptButton property to one of its buttons AND set the DialogResult property for that button to DialogResult.OK, in order for the caller to know if the dialog was accepted or dismissed.

How do I generate a random int number?

 int n = new Random().Next();

You can also give minimum and maximum value to Next() function. Like:

 int n = new Random().Next(5, 10);

Read a text file in R line by line

I suggest you check out chunked and disk.frame. They both have functions for reading in CSVs chunk-by-chunk.

In particular, disk.frame::csv_to_disk.frame may be the function you are after?

Overlapping elements in CSS

the easiest way is to use position:absolute on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative

<div id="container" style="position:relative;">
    <div id="div1" style="position:absolute; top:0; left:0;"></div>
    <div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>

Best way to encode Degree Celsius symbol into web page?

Try to replace it with &deg;, and also to set the charset to utf-8, as Martin suggests.

&deg;C will get you something like this:

Degrees Celsius

Reading and displaying data from a .txt file

You most likely will want to use the FileInputStream class:

int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));

while( (character = inputStream.read()) != -1)
        buffer.append((char) character);

inputStream.close();
System.out.println(buffer);

You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

convert strtotime to date time format in php

$unixtime = 1307595105;
echo $time = date("m/d/Y h:i:s A T",$unixtime);

Where

http://php.net/manual/en/function.date.php

How to style a select tag's option element?

This question is really multiple questions in one. They are different ways of styling something. Here are links to the questions within this question:

Given the lat/long coordinates, how can we find out the city/country?

I spent about an 30min trying to find a code example of how to do this in Javascript. I couldn't find a quick clear answer to the question you posted. So... I made my own. Hopefully people can use this without having to go digging into the API or staring at code they have no idea how to read. Ha if nothing else I can reference this post for my own stuff.. Nice question and thanks for the forum of discussion!

This is utilizing the Google API.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=<YOURGOOGLEKEY>&sensor=false&v=3&libraries=geometry"></script>

.

//CHECK IF BROWSER HAS HTML5 GEO LOCATION
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {

        //GET USER CURRENT LOCATION
        var locCurrent = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

        //CHECK IF THE USERS GEOLOCATION IS IN AUSTRALIA
        var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'latLng': locCurrent }, function (results, status) {
                var locItemCount = results.length;
                var locCountryNameCount = locItemCount - 1;
                var locCountryName = results[locCountryNameCount].formatted_address;

                if (locCountryName == "Australia") {
                    //SET COOKIE FOR GIVING
                    jQuery.cookie('locCountry', locCountryName, { expires: 30, path: '/' }); 
                }
        });
    }
}

How can I change the current URL?

This will do it:

window.history.pushState(null,null,'https://www.google.com');

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

Get attribute name value of <input>

A better way could be using 'this', it takes whatever the name of the 'id' is and uses that. As long as you add the class name called 'mytarget'.

Whenever any of the fields that have target change then it will show an alert box with the name of that field. Just cut and past whole script for it to work!

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
 $('.mytarget').change(function() {
var name1 = $(this).attr("name");
alert(name1);
 });
});
</script>

Name: <input type="text" name="myname" id="myname" class="mytarget"><br />
Age: <input type="text" name="myage" id="myage" class="mytarget"><br />

Python - OpenCV - imread - Displaying Image

This can help you

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );                   // Show our image inside it.

Find the 2nd largest element in an array with minimum number of comparisons

try this.

max1 = a[0].
max2.
for i = 0, until length:
  if a[i] > max:
     max2 = max1.
     max1 = a[i].
     #end IF
  #end FOR
return min2.

it should work like a charm. low in complexity.

here is a java code.

int secondlLargestValue(int[] secondMax){
int max1 = secondMax[0]; // assign the first element of the array, no matter what, sorted or not.
int max2 = 0; // anything really work, but zero is just fundamental.
   for(int n = 0; n < secondMax.length; n++){ // start at zero, end when larger than length, grow by 1. 
        if(secondMax[n] > max1){ // nth element of the array is larger than max1, if so.
           max2 = max1; // largest in now second largest,
           max1 = secondMax[n]; // and this nth element is now max.
        }//end IF
    }//end FOR
    return max2;
}//end secondLargestValue()

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

Javascript - check array for value

If you don't care about legacy browsers:

if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )

if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:

if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )

How to loop through an array of objects in swift

Your userPhotos array is option-typed, you should retrieve the actual underlying object with ! (if you want an error in case the object isn't there) or ? (if you want to receive nil in url):

let userPhotos = currentUser?.photos

for var i = 0; i < userPhotos!.count ; ++i {
    let url = userPhotos![i].url
}

But to preserve safe nil handling, you better use functional approach, for instance, with map, like this:

let urls = userPhotos?.map{ $0.url }

With arrays, why is it the case that a[5] == 5[a]?

For pointers in C, we have

a[5] == *(a + 5)

and also

5[a] == *(5 + a)

Hence it is true that a[5] == 5[a].

Create a hidden field in JavaScript

var input = document.createElement("input");

input.setAttribute("type", "hidden");

input.setAttribute("name", "name_you_want");

input.setAttribute("value", "value_you_want");

//append to form element that you want .
document.getElementById("chells").appendChild(input);

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

You can use this extensions to improve substringWithRange

Swift 2.3

extension String
{   
    func substringWithRange(start: Int, end: Int) -> String
    {
        if (start < 0 || start > self.characters.count)
        {
            print("start index \(start) out of bounds")
            return ""
        }
        else if end < 0 || end > self.characters.count
        {
            print("end index \(end) out of bounds")
            return ""
        }
        let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(end))
        return self.substringWithRange(range)
    }

    func substringWithRange(start: Int, location: Int) -> String
    {
        if (start < 0 || start > self.characters.count)
        {
            print("start index \(start) out of bounds")
            return ""
        }
        else if location < 0 || start + location > self.characters.count
        {
            print("end index \(start + location) out of bounds")
            return ""
        }
        let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(start + location))
        return self.substringWithRange(range)
    }
}

Swift 3

extension String
{
    func substring(start: Int, end: Int) -> String
    {
        if (start < 0 || start > self.characters.count)
        {
            print("start index \(start) out of bounds")
            return ""
        }
        else if end < 0 || end > self.characters.count
        {
            print("end index \(end) out of bounds")
            return ""
        }
        let startIndex = self.characters.index(self.startIndex, offsetBy: start)
        let endIndex = self.characters.index(self.startIndex, offsetBy: end)
        let range = startIndex..<endIndex

        return self.substring(with: range)
    }

    func substring(start: Int, location: Int) -> String
    {
        if (start < 0 || start > self.characters.count)
        {
            print("start index \(start) out of bounds")
            return ""
        }
        else if location < 0 || start + location > self.characters.count
        {
            print("end index \(start + location) out of bounds")
            return ""
        }
        let startIndex = self.characters.index(self.startIndex, offsetBy: start)
        let endIndex = self.characters.index(self.startIndex, offsetBy: start + location)
        let range = startIndex..<endIndex

        return self.substring(with: range)
    }
}

Usage:

let str = "Hello, playground"

let substring1 = str.substringWithRange(0, end: 5) //Hello
let substring2 = str.substringWithRange(7, location: 10) //playground

Current date without time

Try this:

   var mydtn = DateTime.Today;
   var myDt = mydtn.Date;return myDt.ToString("d", CultureInfo.GetCultureInfo("en-US"));

Display animated GIF in iOS

From iOS 11 Photos framework allows to add animated Gifs playback.

Sample app can be dowloaded here

More info about animated Gifs playback (starting from 13:35 min): https://developer.apple.com/videos/play/wwdc2017/505/

enter image description here

Format date as dd/MM/yyyy using pipes

Pipe date format bug fixed in Angular 2.0.0-rc.2, this Pull Request.

Now we can do the conventional way:

{{valueDate | date: 'dd/MM/yyyy'}}

Examples:

Current Version:

Example Angular 8.x.x


Old Versions:

Example Angular 7.x

Example Angular 6.x

Example Angular 4.x

Example Angular 2.x


More info in documentation DatePipe

Android, How can I Convert String to Date?

It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.

One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.

How to add a class to body tag?

I had the same problem,

<body id="body">

Add an ID tag to the body:

$('#body').attr('class',json.class); // My class comes from Ajax/JSON, but change it to whatever you require.

Then switch the class for the body's using the id. This has been tested in Chrome, Internet Explorer, and Safari.

NoClassDefFoundError on Maven dependency

This is due to Morphia jar not being part of your output war/jar. Eclipse or local build includes them as part of classpath, but remote builds or auto/scheduled build don't consider them part of classpath.

You can include dependent jars using plugin.

Add below snippet into your pom's plugins section

    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>

How to delete Certain Characters in a excel 2010 cell

Another option: =MID(A1,2,LEN(A1)-2)

Or this (for fun): =RIGHT(LEFT(A1,LEN(A1)-1),LEN(LEFT(A1,LEN(A1)-1))-1)

Run reg command in cmd (bat file)?

You will probably get an UAC prompt when importing the reg file. If you accept that, you have more rights.

Since you are writing to the 'policies' key, you need to have elevated rights. This part of the registry protected, because it contains settings that are administered by your system administrator.

Alternatively, you may try to run regedit.exe from the command prompt.

regedit.exe /S yourfile.reg

.. should silently import the reg file. See RegEdit Command Line Options Syntax for more command line options.

Python handling socket.error: [Errno 104] Connection reset by peer

You can try to add some time.sleep calls to your code.

It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.

In order to avoid your code from crashing, try to catch this error with try .. except around the urllib2 calls.

Use a loop to plot n charts Python

We can create a for loop and pass all the numeric columns into it. The loop will plot the graphs one by one in separate pane as we are including plt.figure() into it.

import pandas as pd
import seaborn as sns
import numpy as np

numeric_features=[x for x in data.columns if data[x].dtype!="object"]
#taking only the numeric columns from the dataframe.

for i in data[numeric_features].columns:
    plt.figure(figsize=(12,5))
    plt.title(i)
    sns.boxplot(data=data[i])

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

Click event doesn't work on dynamically generated elements

You need to use .live for this to work:

$(".test").live("click", function(){
   alert();
});

or if you're using jquery 1.7+ use .on:

$(".test").on("click", "p", function(){
   alert();
});

How do you run a command for each line of a file?

I know it's late but still

If by any chance you run into windows saved text file with \r\n instead of \n, you might get confused by the output if your command has sth after read line as argument. So do remove \r, for example:

cat file | tr -d '\r' | xargs -L 1 -i echo do_sth_with_{}_as_line

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

I recommend to use both. Rows and cols are required and useful if the client does not support CSS. But as a designer I overwrite them to get exactly the size I wish.

The recommended way to do it is via an external stylesheet e.g.

_x000D_
_x000D_
textarea {_x000D_
  width: 300px;_x000D_
  height: 150px;_x000D_
}
_x000D_
<textarea> </textarea>
_x000D_
_x000D_
_x000D_

SQL Query to concatenate column values from multiple rows in Oracle

For those who must solve this problem using Oracle 9i (or earlier), you will probably need to use SYS_CONNECT_BY_PATH, since LISTAGG is not available.

To answer the OP, the following query will display the PID from Table A and concatenate all the DESC columns from Table B:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT a.pid, seq, description
              FROM table_a a, table_b b
              WHERE a.pid = b.pid(+)
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

There may also be instances where keys and values are all contained in one table. The following query can be used where there is no Table A, and only Table B exists:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT pid, seq, description
              FROM table_b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

All values can be reordered as desired. Individual concatenated descriptions can be reordered in the PARTITION BY clause, and the list of PIDs can be reordered in the final ORDER BY clause.


Alternately: there may be times when you want to concatenate all the values from an entire table into one row.

The key idea here is using an artificial value for the group of descriptions to be concatenated.

In the following query, the constant string '1' is used, but any value will work:

SELECT SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY unique_id ORDER BY pid, seq) rnum, description
       FROM (
              SELECT '1' unique_id, b.pid, b.seq, b.description
              FROM table_b b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1;

Individual concatenated descriptions can be reordered in the PARTITION BY clause.

Several other answers on this page have also mentioned this extremely helpful reference: https://oracle-base.com/articles/misc/string-aggregation-techniques

program cant start because php5.dll is missing

I had the same problem I switched from wamp to xampp and yes PHP was working because my path was still pointing to my old installation. I had forgotten to change it to point to my new php installation which version of php didn't match the rest at all.

Insert a string at a specific index

UPDATE 2016: Here is another just-for-fun (but more serious!) prototype function based on one-liner RegExp approach (with prepend support on undefined or negative index):

/**
 * Insert `what` to string at position `index`.
 */
String.prototype.insert = function(what, index) {
    return index > 0
        ? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
        : what + this;
};

console.log( 'foo baz'.insert('bar ', 4) );  // "foo bar baz"
console.log( 'foo baz'.insert('bar ')    );  // "bar foo baz"

Previous (back to 2012) just-for-fun solution:

var index = 4,
    what  = 'bar ';

'foo baz'.replace(/./g, function(v, i) {
    return i === index - 1 ? v + what : v;
});  // "foo bar baz"

What are good ways to prevent SQL injection?

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

Set select option 'selected', by value

a simple answer is, at html

<select name="ukuran" id="idUkuran">
    <option value="1000">pilih ukuran</option>
    <option value="11">M</option>
    <option value="12">L</option>
    <option value="13">XL</option>
</select>

on jquery, call below function by button or whatever

$('#idUkuran').val(11).change();

it simple and 100% works, coz its taken from my work... :) hope its help..

How to increase font size in the Xcode editor?

Go to

Xcode menu > Preferences > Font & Color > Category

Double-click on Plain Text, a popup menu will come up. Change it from there.

What's the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA in the above example). You may use prefetch_related for anything that you can use select_related for.

The tradeoffs are that prefetch_related has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.

Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related has the extra benefit that a single object is used to represent each object in the database. With select_related duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

I second Shobhit Verma, and I have a little note to add : in his post he told that in Chrome (Opera for myself) the players need to be muted in order for the autoplay to succeed... And ironically, if you elevate the volume after load, it will still play... It's like all those anti-pop-ups mechanic that ignore invisible frame slid into your code... php-echoed html and javascript is : 10-second setTimeout onLoad of body tag that rises volume to maximum, video with autoplay and muted='muted' (yeah that $muted_code part is = "muted='muted")

echo "<body style='margin-bottom:0pt; margin-top:0pt; margin-left:0pt; margin-right:0pt' onLoad=\"setTimeout(function() {var vid = document.getElementById('hourglass_video'); vid.volume = 1.0;},10000);\">";
    echo "<div id='hourglass_container' width='100%' height='100%' align='center' style='text-align:right; vertical-align:bottom'>";
    echo "<video autoplay {$muted_code}title=\"!!! Pausing this video will immediately end your turn!!!\" oncontextmenu=\"dont_stop_hourglass(event);\" onPause=\"{$action}\" id='hourglass_video' frameborder='0' style='width:95%; margin-top:28%'>";

UTF-8, UTF-16, and UTF-32

As mentioned, the difference is primarily the size of the underlying variables, which in each case get larger to allow more characters to be represented.

However, fonts, encoding and things are wickedly complicated (unnecessarily?), so a big link is needed to fill in more detail:

http://www.cs.tut.fi/~jkorpela/chars.html#ascii

Don't expect to understand it all, but if you don't want to have problems later it's worth learning as much as you can, as early as you can (or just getting someone else to sort it out for you).

Paul.

Set IDENTITY_INSERT ON is not working

The relevant part of the error message is

...when a column list is used...

You are not using a column list, you are using SELECT *. Use a column list instead:

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] ON 

INSERT INTO [MyDB].[dbo].[Equipment] (Col1, Col2, ...)
SELECT Col1, Col2, ... FROM [MyDBQA].[dbo].[Equipment] 

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] OFF 

Show a message box from a class in c#?

using System.Windows.Forms;
...
MessageBox.Show("Hello World!");

How can I make Visual Studio wrap lines at 80 characters?

Tools >> Options >> Text Editor >> All Languages >> General >> Select Word Wrap.

I dont know if you can select a specific number of columns?

PHP - Insert date into mysql

try CAST function in MySQL:

mysql_query("INSERT INTO data_table (title, date_of_event)
VALUES('". $_POST['post_title'] ."',
CAST('". $date ."' AS DATE))") or die(mysql_error()); 

Android failed to load JS bundle

I found this to be weird but I got a solution. I noticed that every once in a while my project folder went read-only and I couldn't save it from VS. So I read a suggestion to transfer NPM from local user PATH to system-wide PATH global variable, and it worked like a charm.

How do you disable viewport zooming on Mobile Safari?

for iphones safari up to iOS 10 "viewport" is not a solution, i don't like this way, but i have used this javascript code and it helped me

 document.addEventListener('touchmove', function(event) {
    event = event.originalEvent || event;
    if(event.scale > 1) {
      event.preventDefault();
    }
  }, false);

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

From commons-lang3

org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)

How to print all key and values from HashMap in Android?

You can do it easier with Gson:

Log.i(TAG, "SomeText: " + new Gson().toJson(yourMap));

The result will look like:

I/YOURTAG: SomeText: {"key1":"value1","key2":"value2"}

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Rather than finding top view controller, one can use

viewController.modalPresentationStyle = UIModalPresentationStyle.currentContext

Where viewController is the controller which you want to present This is useful when there are different kinds of views in hierarchy like TabBar, NavBar, though others seems to be correct but more sort of hackish

The other presentation style can be found on apple doc

How to check visibility of software keyboard in Android?

Think has a easy way, like this:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.isActive();

You can also see if him is active in a specific view:

imm.isActive(View v);

Bash script to calculate time elapsed

Try the following code:

start=$(date +'%s') && sleep 5 && echo "It took $(($(date +'%s') - $start)) seconds"

PHP: Get the key from an array in a foreach loop

Try this:

foreach($samplearr as $key => $item){
  print "<tr><td>" 
      . $key 
      . "</td><td>"  
      . $item['value1'] 
      . "</td><td>" 
      . $item['value2'] 
      . "</td></tr>";
}

format a Date column in a Data Frame

try this package, works wonders, and was made for date/time...

library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)

How to right align widget in horizontal linear layout Android?

this is my xml, dynamic component to align right, in my case i use 3 button

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/checkinInputCodeMember">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="7"
                android:orientation="vertical" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_extends"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="3"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_checkout"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="2"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/checkinButtonScanQrCodeMember"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="1"/>


        </LinearLayout>

and the result

you can hide the right first button with change visibility GONE, and this my code

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/checkinInputCodeMember">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="7"
                android:orientation="vertical" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_extends"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="3"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_checkout"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="2"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/checkinButtonScanQrCodeMember"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:text="1"
                android:textColor="@color/colorAccent"
                **android:visibility="gone"**/>


        </LinearLayout>

still align right, after visibility gone first right component

result code 1

result code 2

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

In numpy, index and dimension numbering starts with 0. So axis 0 means the 1st dimension. Also in numpy a dimension can have length (size) 0. The simplest case is:

In [435]: x = np.zeros((0,), int)
In [436]: x
Out[436]: array([], dtype=int32)
In [437]: x[0]
...
IndexError: index 0 is out of bounds for axis 0 with size 0

I also get it if x = np.zeros((0,5), int), a 2d array with 0 rows, and 5 columns.

So someplace in your code you are creating an array with a size 0 first axis.

When asking about errors, it is expected that you tell us where the error occurs.

Also when debugging problems like this, the first thing you should do is print the shape (and maybe the dtype) of the suspected variables.

Applied to pandas

Resolving the error:

  1. Use a try-except block
  2. Verify the size of the array is not 0
    • if x.size != 0:

How to add an Android Studio project to GitHub

You need to create the project on GitHub first. After that go to the project directory and run in terminal:

git init
git remote add origin https://github.com/xxx/yyy.git
git add .
git commit -m "first commit"
git push -u origin master

How do I get first name and last name as whole name in a MYSQL query?

You can use a query to get the same:

SELECT CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) AS Name FROM TableName;

Note: This query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL"

To avoid above we can use the IsNull keyword to get the same.

SELECT Concat(Ifnull(FirstName,' ') ,' ', Ifnull(MiddleName,' '),' ', Ifnull(Lastname,' ')) FROM TableName;

If anyone containing null value the ' ' (space) will add with next value.

How to create a video from images with FFmpeg?

cat *.png | ffmpeg -f image2pipe -i - output.mp4

from wiki

Using custom std::set comparator

1. Modern C++20 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;

We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.

Online demo

2. Modern C++11 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);

Before C++20 we need to pass lambda as argument to set constructor

Online demo

3. Similar to first solution, but with function instead of lambda

Make comparator as usual boolean function

bool cmp(int a, int b) {
    return ...;
}

Then use it, either this way:

std::set<int, decltype(cmp)*> s(cmp);

Online demo

or this way:

std::set<int, decltype(&cmp)> s(&cmp);

Online demo

4. Old solution using struct with () operator

struct cmp {
    bool operator() (int a, int b) const {
        return ...
    }
};

// ...
// later
std::set<int, cmp> s;

Online demo

5. Alternative solution: create struct from boolean function

Take boolean function

bool cmp(int a, int b) {
    return ...;
}

And make struct from it using std::integral_constant

#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;

Finally, use the struct as comparator

std::set<X, Cmp> set;

Online demo

Java equivalent to #region in C#

There's no such standard equivalent. Some IDEs - Intellij, for instance, or Eclipse - can fold depending on the code types involved (constructors, imports etc.), but there's nothing quite like #region.

Get current location of user in Android without using GPS or internet

No, you cannot currently get location without using GPS or internet.

Location techniques based on WiFi, Cellular, or Bluetooth work with the help of a large database that is constantly being updated. A device scans for transmitter IDs and then sends these in a query through the internet to a service such as Google, Apple, or Skyhook. That service responds with a location based on previous wireless surveys from known locations. Without internet access, you have to have a local copy of such a database and keep this up to date. For global usage, this is very impractical.

Theoretically, a mobile provider could provide local data service only but no access to the internet, and then answer location queries from mobile devices. Mobile providers don't do this; no one wants to pay for this kind of restricted data access. If you have data service through your mobile provider, then you have internet access.

In short, using LocationManager.NETWORK_PROVIDER or android.hardware.location.network to get location requires use of the internet.

Using the last known position requires you to have had GPS or internet access very recently. If you just had internet, presumably you can adjust your position or settings to get internet again. If your device has not had GPS or internet access, the last known position feature will not help you.

Without GPS or internet, you could:

  1. Take pictures of the night sky and use the current time to estimate your location based on a star chart. This would probably require additional equipment to ensure that the angles for your pictures are correctly measured.
  2. Use an accelerometer to track location starting from a known position. The accumulation of error in this kind of approach makes it impractical for most situations.

"Instantiating" a List in Java?

List is an interface, not a concrete class.
An interface is just a set of functions that a class can implement; it doesn't make any sense to instantiate an interface.

ArrayList is a concrete class that happens to implement this interface and all of the methods in it.

How to print a query string with parameter values when using Hibernate

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" 
      value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
</appender>

<logger name="org.hibernate" additivity="false">
    <level value="INFO" />
    <appender-ref ref="console" />
</logger>

<logger name="org.hibernate.type" additivity="false">
    <level value="TRACE" />
    <appender-ref ref="console" />
</logger>

Determining if an Object is of primitive type

I think this happens due to auto-boxing.

int i = 3;
Object o = i;
o.getClass().getName(); // prints Integer

You may implement a utility method that matches these specific boxing classes and gives you if a certain class is primitive.

public static boolean isWrapperType(Class<?> clazz) {
    return clazz.equals(Boolean.class) || 
        clazz.equals(Integer.class) ||
        clazz.equals(Character.class) ||
        clazz.equals(Byte.class) ||
        clazz.equals(Short.class) ||
        clazz.equals(Double.class) ||
        clazz.equals(Long.class) ||
        clazz.equals(Float.class);
}

How to use a variable for the database name in T-SQL?

You can also use sqlcmd mode for this (enable this on the "Query" menu in Management Studio).

:setvar dbname "TEST" 

CREATE DATABASE $(dbname)
GO
ALTER DATABASE $(dbname) SET COMPATIBILITY_LEVEL = 90
GO
ALTER DATABASE $(dbname) SET RECOVERY SIMPLE 
GO

EDIT:

Check this MSDN article to set parameters via the SQLCMD tool.

How do I create 7-Zip archives with .NET?

SharpCompress is in my opinion one of the smartest compression libraries out there. It supports LZMA (7-zip), is easy to use and under active development.

As it has LZMA streaming support already, at the time of writing it unfortunately only supports 7-zip archive reading. BUT archive writing is on their todo list (see readme). For future readers: Check to get the current status here: https://github.com/adamhathcock/sharpcompress/blob/master/FORMATS.md

What are the various "Build action" settings in Visual Studio project properties and what do they do?

  • Fakes: Part of the Microsoft Fakes (Unit Test Isolation) Framework. Not available on all Visual Studio versions. Fakes are used to support unit testing in your project, helping you isolate the code you are testing by replacing other parts of the application with stubs or shims. More here: https://msdn.microsoft.com/en-us/library/hh549175.aspx

Centering a button vertically in table cell, using Twitter Bootstrap

To fix this, i put this class on the webpage

<style>                        
    td.vcenter {
        vertical-align: middle !important;
        text-align: center !important;
    }
</style>

and this in my TemplateField

<asp:TemplateField ItemStyle-CssClass="vcenter">

as the CSS class points directly to the td (tabledata) element and has the !important statment at the end each setting. It will over rule bootsraps CSS class settings.

Hope it helps

Example of Mockito's argumentCaptor

I agree with what @fge said, more over. Lets look at example. Consider you have a method:

class A {
    public void foo(OtherClass other) {
        SomeData data = new SomeData("Some inner data");
        other.doSomething(data);
    }
}

Now if you want to check the inner data you can use the captor:

// Create a mock of the OtherClass
OtherClass other = mock(OtherClass.class);

// Run the foo method with the mock
new A().foo(other);

// Capture the argument of the doSomething function
ArgumentCaptor<SomeData> captor = ArgumentCaptor.forClass(SomeData.class);
verify(other, times(1)).doSomething(captor.capture());

// Assert the argument
SomeData actual = captor.getValue();
assertEquals("Some inner data", actual.innerData);

How to scp in Python?

I don't think there's any one module that you can easily download to implement scp, however you might find this helpful: http://www.ibm.com/developerworks/linux/library/l-twist4.html

C++ array initialization

Yes, I believe it should work and it can also be applied to other data types.

For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.

XMLHttpRequest status 0 (responseText is empty)

status is 0 when your html file containing the script is opened in the browser via the file scheme. Make sure to place the files in your server (apache or tomcat whatever) and then open it via http protocol in the browser. (i.e. http://localhost/myfile.html) This is the solution.

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

I believe that you can omit updating the "non-desired" columns by adjusting the other answers as follows:

update table set
    columnx = (case when condition1 then 25 end),
    columny = (case when condition2 then 25 end)`

As I understand it, this will update only when the condition is met.

After reading all the comments, this is the most efficient:

Update table set ColumnX = 25 where Condition1
 Update table set ColumnY = 25 where Condition1`

Sample Table:

CREATE TABLE [dbo].[tblTest](
    [ColX] [int] NULL,
    [ColY] [int] NULL,
    [ColConditional] [bit] NULL,
    [id] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]

Sample Data:

Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1)
Insert into tblTest (ColX, ColY, ColConditional) values (1, null, null)
Insert into tblTest (ColX, ColY, ColConditional) values (2, null, null)
Insert into tblTest (ColX, ColY, ColConditional) values (null, 1, null)
Insert into tblTest (ColX, ColY, ColConditional) values (null, 2, null)

Now I assume you can write a conditional that handles nulls. For my example, I am assuming you have written such a conditional that evaluates to True, False or Null. If you need help with this, let me know and I will do my best.

Now running these two lines of code does infact change X to 25 if and only if ColConditional is True(1) and Y to 25 if and only if ColConditional is False(0)

Update tblTest set ColX = 25 where ColConditional = 1
Update tblTest set ColY = 25 where ColConditional = 0

P.S. The null case was never mentioned in the original question or any updates to the question, but as you can see, this very simple answer handles them anyway.

Visual Studio replace tab with 4 spaces?

None of these answer were working for me on my macbook pro. So what i had to do was go to:

Preferences -> Source Code -> Code Formatting -> C# source code.

From here I could change my style and spacing tabs etc. This is the only project i have where the lead developer has different formatting than i do. It was a pain in the butt that my IDE would format my code different than theirs.

How to fix a header on scroll

Or just simply add a span tag with the height of the fixed header set as its height then insert it next to the sticky header:

$(function() {
  var $span_height = $('.fixed-header').height;
  var $span_tag = '<span style="display:block; height:' + $span_height + 'px"></span>';

  $('.fixed-header').after($span_tag);
});

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

Even if I'm too late but this might help someone who will get stuck too in the coming days. I faced the same issue but my problem was running many commands with npm start. I was running create tables and insert data before start the app and make 10 sec exceeds before running. So I removed those commands and problem solved.

Thanks

100% width in React Native Flexbox

First add Dimension component:

import { AppRegistry, Text, View,Dimensions } from 'react-native';

Second define Variables:

var height = Dimensions.get('window').height;
var width = Dimensions.get('window').width;

Third put it in your stylesheet:

textOutputView: {
    flexDirection:'row',
    paddingTop:20,
    borderWidth:1,
    borderColor:'red',
    height:height*0.25,
    backgroundColor:'darkgrey',
    justifyContent:'flex-end'
}

Actually in this example I wanted to make responsive view and wanted to view only 0.25 of the screen view so I multiplied it with 0.25, if you wanted 100% of the screen don't multiply it with any thing like this:

textOutputView: {
    flexDirection:'row',
    paddingTop:20,
    borderWidth:1,
    borderColor:'red',
    height:height,
    backgroundColor:'darkgrey',
    justifyContent:'flex-end'
}

#1071 - Specified key was too long; max key length is 1000 bytes

I had this issue, and solved by following:

Cause

There is a known bug with MySQL related to MyISAM, the UTF8 character set and indexes that you can check here.

Resolution

  • Make sure MySQL is configured with the InnoDB storage engine.

  • Change the storage engine used by default so that new tables will always be created appropriately:

    set GLOBAL storage_engine='InnoDb';

  • For MySQL 5.6 and later, use the following:

    SET GLOBAL default_storage_engine = 'InnoDB';

  • And finally make sure that you're following the instructions provided in Migrating to MySQL.

Reference

show all tags in git log

git log --no-walk --tags --pretty="%h %d %s" --decorate=full

This version will print the commit message as well:

 $ git log --no-walk --tags --pretty="%h %d %s" --decorate=full
3713f3f  (tag: refs/tags/1.0.0, tag: refs/tags/0.6.0, refs/remotes/origin/master, refs/heads/master) SP-144/ISP-177: Updating the package.json with 0.6.0 version and the README.md.
00a3762  (tag: refs/tags/0.5.0) ISP-144/ISP-205: Update logger to save files with optional port number if defined/passed: Version 0.5.0
d8db998  (tag: refs/tags/0.4.2) ISP-141/ISP-184/ISP-187: Fixing the bug when loading the app with Gulp and Grunt for 0.4.2
3652484  (tag: refs/tags/0.4.1) ISP-141/ISP-184: Missing the package.json and README.md updates with the 0.4.1 version
c55eee7  (tag: refs/tags/0.4.0) ISP-141/ISP-184/ISP-187: Updating the README.md file with the latest 1.3.0 version.
6963d0b  (tag: refs/tags/0.3.0) ISP-141/ISP-184: Add support for custom serializers: README update
4afdbbe  (tag: refs/tags/0.2.0) ISP-141/ISP-143/ISP-144: Fixing a bug with the creation of the logs
e1513f1  (tag: refs/tags/0.1.0) ISP-141/ISP-143: Betterr refactoring of the Loggers, no dependencies, self-configuration for missing settings.

How can I find the first occurrence of a sub-string in a python string?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

Unable to generate an explicit migration in entity framework

There is an ambiguity and so error. Best way is to exclude the current migration file and create new migration(add-migration) file and then copy the content of new migration to excluded file and include it again and run update-database command.

Tomcat 8 Maven Plugin for Java 8

Plugin run Tomcat 7.0.47:

mvn org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run

 ...
 INFO: Starting Servlet Engine: Apache Tomcat/7.0.47

This is sample to run plugin with Tomcat 8 and Java 8: Cargo embedded tomcat: custom context.xml

SQLAlchemy IN clause

Assuming you use the declarative style (i.e. ORM classes), it is pretty easy:

query = db_session.query(User.id, User.name).filter(User.id.in_([123,456]))
results = query.all()

db_session is your database session here, while User is the ORM class with __tablename__ equal to "users".

Return index of greatest value in an array

A stable version of this function looks like this:

// not defined for empty array
function max_index(elements) {
    var i = 1;
    var mi = 0;
    while (i < elements.length) {
        if (!(elements[i] < elements[mi]))
            mi = i;
        i += 1;
    }
    return mi;
}

Android Studio update -Error:Could not run build action using Gradle distribution

Go on Project->Settings->Compiler(Gradle-based android project), find the text field "VM option" and put there:

-Xmx512m -XX:MaxPermSize=512m

This shouls solve the issue in any case the error shown in the gradle message window is "Could not reserve enough space for object heap"

Hope this helps

Way to get all alphabetic chars in an array in PHP?

Another way:

$c = 'A';
$chars = array($c);
while ($c < 'Z') $chars[] = ++$c;