Programs & Examples On #Code editor

How to remove tab indent from several lines in IDLE?

For IDLE, select the lines, then open the "Format" menu. (Between "Edit" and "Run" if you're having trouble finding it.) This will also give you the keyboard shortcut, for me it turned out that dedent shortcut was "Ctrl+["

How to collapse blocks of code in Eclipse?

If you want folding an all your editors, I found you can enable Folding in

Preferences > Editors > Structured Text Editors

Enable Folding

Why does the Visual Studio editor show dots in blank spaces?

I had the same problem and resolved by pressing Ctrl + R , Ctrl + W.

bootstrap 3 tabs not working properly

for some weird reason bootstrap tabs were not working for me until i was using href like:-

<li class="nav-item"><a class="nav-link" href="#a" data-toggle="tab">First</a></li>

but it started working as soon as i replaced href with data-target like:-

<li class="nav-item"><a class="nav-link" data-target="#a" data-toggle="tab">First</a></li>

ORA-01036: illegal variable name/number when running query through C#

This error happens when you are also missing cmd.CommandType = System.Data.CommandType.StoredProcedure;

What is the use of hashCode in Java?

From the Javadoc:

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)

How to convert date to string and to date again?

tl;dr

How to convert date to string and to date again?

LocalDate.now().toString()

2017-01-23

…and…

LocalDate.parse( "2017-01-23" )

java.time

The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.

Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.

If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;

ISO 8601

Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.

That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.

String s = ld.toString() ;

To parse:

LocalDate ld = LocalDate.parse( s ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Hashmap with Streams in Java 8 Streams to collect value of Map

What you need to do is create a Stream out of the Map's .entrySet():

// Map<K, V> --> Set<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
map.entrySet().stream()

From the on, you can .filter() over these entries. For instance:

// Stream<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
.filter(entry -> entry.getKey() == 1)

And to obtain the values from it you .map():

// Stream<Map.Entry<K, V>> --> Stream<V>
.map(Map.Entry::getValue)

Finally, you need to collect into a List:

// Stream<V> --> List<V>
.collect(Collectors.toList())

If you have only one entry, use this instead (NOTE: this code assumes that there is a value; otherwise, use .orElse(); see the javadoc of Optional for more details):

// Stream<V> --> Optional<V> --> V
.findFirst().get()

Not able to pip install pickle in python 3.6

You can pip install pickle by running command pip install pickle-mixin. Proceed to import it using import pickle. This can be then used normally.

file_get_contents() how to fix error "Failed to open stream", "No such file"

The URL is missing the protocol information. PHP thinks it is a filesystem path and tries to access the file at the specified location. However, the location doesn't actually exist in your filesystem and an error is thrown.

You'll need to add http or https at the beginning of the URL you're trying to get the contents from:

$json = json_decode(file_get_contents('http://...'));

As for the following error:

Unable to find the wrapper - did you forget to enable it when you configured PHP?

Your Apache installation probably wasn't compiled with SSL support. You could manually try to install OpenSSL and use it, or use cURL. I personally prefer cURL over file_get_contents(). Here's a function you can use:

function curl_get_contents($url)
{
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}

Usage:

$url = 'https://...';
$json = json_decode(curl_get_contents($url));

Accessing value inside nested dictionaries

My implementation:

def get_nested(data, *args):
    if args and data:
        element  = args[0]
        if element:
            value = data.get(element)
            return value if len(args) == 1 else get_nested(value, *args[1:])

Example usage:

>>> dct={"foo":{"bar":{"one":1, "two":2}, "misc":[1,2,3]}, "foo2":123}
>>> get_nested(dct, "foo", "bar", "one")
1
>>> get_nested(dct, "foo", "bar", "two")
2
>>> get_nested(dct, "foo", "misc")
[1, 2, 3]
>>> get_nested(dct, "foo", "missing")
>>>

There are no exceptions raised in case a key is missing, None value is returned in that case.

How to vertically align label and input in Bootstrap 3?

The bootstrap 3 docs for horizontal forms let you use the .form-horizontal class to make your form labels and inputs vertically aligned. The structure for these forms is:

<form class="form-horizontal" role="form">
  <div class="form-group">
    <label for="input1" class="col-lg-2 control-label">Label1</label>
    <div class="col-lg-10">
      <input type="text" class="form-control" id="input1" placeholder="Input1">
    </div>
  </div>
  <div class="form-group">
    <label for="input2" class="col-lg-2 control-label">Label2</label>
    <div class="col-lg-10">
      <input type="password" class="form-control" id="input2" placeholder="Input2">
    </div>
  </div>
</form>

Therefore, your form should look like this:

<form class="form-horizontal" role="form">
    <div class="form-group">
        <div class="col-xs-3">
            <label for="class_type"><h2><span class=" label label-primary">Class Type</span></h2></label>
        </div>
        <div class="col-xs-2">
            <select id="class_type" class="form-control input-lg" autocomplete="off">
                <option>Economy</option>
                <option>Premium Economy</option>
                <option>Club World</option>
                <option>First Class</option>
            </select>
        </div>
    </div>
</form>

Validating Phone Numbers Using Javascript

<!DOCTYPE html>
<html>
    <head>
        <style>
           .container__1{
               max-width: 450px;
               font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
           }
           .container__1 label{
               display: block;
               margin-bottom: 10px;
           }
           .container__1 label > span{
               float: left;
               width: 100px;
               color: #F072A9;
               font-weight: bold;
               font-size: 13px;
               text-shadow: 1px 1px 1px #fff;
           }
           .container__1 fieldset{
               border-radius: 10px;
               -webkit-border-radious:10px;
               -moz-border-radoius: 10px;
               margin: 0px 0px 0px 0px;
               border: 1px solid #FFD2D2;
               padding: 20px;
               background:#FFF4F4 ;
               box-shadow: inset 0px 0px 15px #FFE5E5;


           }
           .container__1 fieldset legend{
               color: #FFA0C9;
               border-top: 1px solid #FFD2D2 ;
               border-left: 1px solid #FFD2D2 ;
               border-right: 1px solid #FFD2D2 ;
               border-radius: 5px 5px 0px 0px;
               background: #FFF4F4;
               padding: 0px 8px 3px 8px;
               box-shadow: -0px -1px 2px #F1F1F1;
               font-weight: normal;
               font-size: 12px;
           }
           .container__1 textarea{
               width: 250px;
               height: 100px;
           }.container__1 input[type=text],
           .container__1 input[type=email],
           .container__1 select{
               border-radius: 3px;
               border: 1px solid #FFC2DC;
               outline: none;
               color: #F072A9;
               padding: 5px 8px 5px 8px;
               box-shadow: inset 1px 1px 4px #FFD5E7;
               background: #FFEFF6;
               

           }
           .container__1 input[type=submit],
           .container__1 input[type=button]{
               background: #EB3B88;
               border: 1px solid #C94A81;
               padding: 5px 15px 5px 15px;
               color: #FFCBE2;
               box-shadow: inset -1px -1px 3px #FF62A7;
               border-radius: 3px;
               font-weight: bold;
           }
           .required{
               color: red;
           }
        </style>
    </head>
    <body>
        <div class="container__1">
            <form name="RegisterForm" onsubmit="return(SubmitClick())">
                <fieldset>
                    <legend>Personal</legend>
                    <label for="field1"><span >Name<span class="required">*</span><input id="name" type="text" class="input-field" name="Name" value=""</label>
                    <label for="field2"><span >Email<span class="required">*</span><input placeholder="Ex: [email protected]" id="email" type="email" class="input-field" name="Email" value=""</label>
                    <label for="field3"><span >Phone<span class="required">*</span><input placeholder="+919853004369" id="mobile" type="text" class="input-field" name="Mobile" value=""</label>
                    <label for="field4">
                        <span>Subject</span>
                        <select name="subject" id="subject" class="select-field">
                            <option value="none">Choose Your Sub..</option>
                            <option value="Appointment">Appiontment</option>
                            <option value="Interview">Interview</option>
                            <option value="Regarding a post">Regarding a post</option>
                        </select>
                    </label>
                    <label><span></span><input type="submit"  ></label>
                </fieldset>
            </form>
        </div>
    </body>
    <script>
        function SubmitClick(){
        _name = document.querySelector('#name').value;
        _email = document.querySelector('#email').value;
        _mobile = document.querySelector('#mobile').value;
        _subject = document.querySelector('#subject').value;
          if(_name == '' || _name == null ){
              alert('Enter Your Name');
              document.RegisterForm.Name.focus();
              return false; 
          } 
          var atPos = _email.indexOf('@');
         var dotPos = _email.lastIndexOf('.');

          if(_email == '' || atPos<1 || (dotPos - atPos)<2){
              alert('Provide Your Correct Email address');
              document.RegisterForm.Email.focus();
              return false;
          }
          var regExp = /^\+91[0-9]{10}$/;
          if(_mobile == '' || !regExp.test(_mobile)){
              alert('Please Provide your Mobile number as Ex:- +919853004369');
              document.RegisterForm.Mobile.focus();
              return false;
          }
          if(_subject == 'none'){
              alert('Please choose a subject');
              document.RegisterForm.subject.focus();
              return false;
          }else{
            alert (`success!!!:--'\n'Name:${_name},'\n' Mobile: ${_mobile},'\n' Email:${_email},'\n' Subject:${_subject},`)
          }
        
          
        }
    </script>
</html>

What is the Record type in typescript?

A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.

For example, say I have a Union like this:

type CatNames = "miffy" | "boris" | "mordred";

Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.

type CatList = Record<CatNames, {age: number}>

If I want to satisfy this CatList, I must create an object like this:

const cats:CatList = {
  miffy: { age:99 },
  boris: { age:16 },
  mordred: { age:600 }
}

You get very strong type safety:

  • If I forget a cat, I get an error.
  • If I add a cat that's not allowed, I get an error.
  • If I later change CatNames, I get an error. This is especially useful because CatNames is likely imported from another file, and likely used in many places.

Real-world React example.

I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes

I had a union like this:

type Statuses = "failed" | "complete";

I used this to create an object like this:

const icons: Record<
  Statuses,
  { iconType: IconTypes; iconColor: IconColors }
> = {
  failed: {
    iconType: "warning",
    iconColor: "red"
  },
  complete: {
    iconType: "check",
    iconColor: "green"
  };

I could then render by destructuring an element from the object into props, like so:

const Status = ({status}) => <Icon {...icons[status]} />

If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.

Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.

From a Sybase Database, how I can get table description ( field names and types)?

In the Sybase version I use, the following gives list of columns for selected table

select *
FROM sys.syscolumns sc
where tname = 'YOUR_TABLE_NAME'
--and creator='YOUR_USER_NAME' --if you want to further restrict tables
--according to the user name that created it

How do I merge a git tag onto a branch

Just complementing the answer.

Merging the last tag on a branch:

git checkout my-branch
git merge $(git describe --tags $(git rev-list --tags --max-count=1))

Inspired by https://gist.github.com/rponte/fdc0724dd984088606b0

Get Unix timestamp with C++

#include <iostream>
#include <sys/time.h>

using namespace std;

int main ()
{
  unsigned long int sec= time(NULL);
  cout<<sec<<endl;
}

SQL Developer with JDK (64 bit) cannot find JVM

For Windows Users: If anyone downloaded a non-jre version and faced issue, then later trying with the JRE version and still facing the issue, you need to delete SQLDeveloper folder inside "%AppData%\sqldeveloper". After deleting try opening sqldeveloper.exe again.

Dynamic SELECT TOP @var In SQL Server

Its also possible to use dynamic SQL and execute it with the exec command:

declare @sql  nvarchar(200), @count int
set @count = 10
set @sql = N'select top ' + cast(@count as nvarchar(4)) + ' * from table'
exec (@sql)

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I would still recommend Firebug. Not only it can debug JS within your JSP files, it can enhance debugging experience with addons like JS Deminifier (if your production JS is minified), FireQuery, FireRainbow and more.

There is also Firebug lite which is nothing but a bookmarklet. It lets you do limited things but still is useful.

Chrome as a developer console built-in that would let you modify javascript.

Using these tools, you should be able to inject your own JS too.

Find control by name from Windows Forms controls

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

If Controls.Find is not found "textBox1" => error. You must add code.

If(tbx != null)

Edit:

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
   tbx.Text = "found!";

Powershell send-mailmessage - email to multiple recipients

You must first convert the string to a string array, like this:

$recipients = "Marcel <[email protected]>,Marcelt <[email protected]>"
[string[]]$To = $recipients.Split(',')

Then use Send-MailMessage like this:

Send-MailMessage -From "[email protected]" -To $To -subject "New files" -body "$teloadmin" -BodyAsHtml -priority High -dno onSuccess, onFailure -smtpServer 192.168.170.61

What is the better API to Reading Excel sheets in java - JXL or Apache POI

I am not familiar with JXL and but we use POI. POI is well maintained and can handle both the binary .xls format and the new xml based format that was introduced in Office 2007.

CSV files are not excel files, they are text based files, so these libraries don't read them. You will need to parse out a CSV file yourself. I am not aware of any CSV file libraries, but I haven't looked either.

Remove characters from NSString?

You can try this

- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
    while ([str rangeOfString:@"  "].location != NSNotFound) {
        str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return str;
}

Hope this will help you out.

How to concatenate items in a list to a single string?

It's very useful for beginners to know why join is a string method.

It's very strange at the beginning, but very useful after this.

The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).

.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).

Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.

>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'

>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'

No restricted globals

Try adding window before location (i.e. window.location).

How to Sort a List<T> by a property in the object

Make use of LiNQ OrderBy

List<Order> objListOrder=new List<Order> ();
    objListOrder=GetOrderList().OrderBy(o=>o.orderid).ToList();

Can a relative sitemap url be used in a robots.txt?

Good technical & logical question my dear friend. No in robots.txt file you can't go with relative URL of the sitemap; you need to go with the complete URL of the sitemap.

It's better to go with "sitemap: https://www.example.com/sitemap_index.xml"

In the above URL after the colon gives space. I also like to support Deepak.

Convert Mat to Array/Vector in OpenCV

You can use iterators:

Mat matrix = ...;

std::vector<float> vec(matrix.begin<float>(), matrix.end<float>());

How do I center text horizontally and vertically in a TextView?

android:gravity="center" 

This will do the trick

python-dev installation error: ImportError: No module named apt_pkg

I met this problem when doing sudo apt-get update. My env is debian8, with python2.7 + 3.4(default) + 3.5.

The following code will only re-create a apt_pkg....so file for python 3.5

sudo apt-get install python3-apt --reinstall

The following code solved my problem,

cd /usr/lib/python3/dist-packages
sudo ln -s apt_pkg.cpython-{35m,34m}-x86_64-linux-gnu.so

So, obviously, python3-apt checks the highest python version, instead of the current python version in use.

Error: The type exists in both directories

This has been answered in a separate question and resolved the problem for me. Be sure to vote up the original person's answer.

ASP.Net error: "The type 'foo' exists in both "temp1.dll" and "temp2.dll"

Add the batch="false" attribute to the "compilation" element of the web.config file.

This problem occurs because of the way in which ASP.NET 2.0 uses the application references and the folder structure of the application to compile the application. If the batch property of the element in the web.config file for the application is set to true, ASP.NET 2.0 compiles each folder in the application into a separate assembly.

http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=1995

http://support.microsoft.com/kb/919284

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If it works fine on your local environment, probably your remote server's IP is being blocked by the server at the target URL you've set for cURL to use. You need to verify that your remote server is allowed to access the URL you've set for CURLOPT_URL.

Change border color on <select> HTML form

No, the <select> control is a system-level control, not a client-level control in IE. A few versions back it didn't even play nicely-with z-index, putting itself on top of virtually everything.

To do anything fancy you'll have to emulate the functionality using CSS and your own elements.

When is it appropriate to use UDP instead of TCP?

It's not always clear cut. However, if you need guaranteed delivery of packets with no loss and in the right sequence then TCP is probably what you want.

On the other hand UDP is appropriate for transmitting short packets of information where the sequence of the information is less important or where the data can fit into a single packet.

It's also appropriate when you want to broadcast the same information to many users.

Other times, it's appropriate when you are sending sequenced data but if some of it goes missing you're not too concerned (e.g. a VOIP application).

Some protocols are more complex because what's needed are some (but not all) of the features of TCP, but more than what UDP provides. That's where the application layer has to implement the additional functionality. In those cases, UDP is also appropriate (e.g. Internet radio, order is important but not every packet needs to get through).

Examples of where it is/could be used 1) A time server broadcasting the correct time to a bunch of machines on a LAN. 2) VOIP protocols 3) DNS lookups 4) Requesting LAN services e.g. where are you? 5) Internet radio 6) and many others...

On unix you can type grep udp /etc/services to get a list of UDP protocols implemented today... there are hundreds.

Subtract minute from DateTime in SQL Server 2005

SELECT DATEADD(minute, -15, '2000-01-01 08:30:00'); 

The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like

SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00'); 

where @h is the hour part of your string and @m is the minute part of your string

EDIT:

Here is a better way:

SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)

Custom method names in ASP.NET Web API

By default the route configuration follows RESTFul conventions meaning that it will accept only the Get, Post, Put and Delete action names (look at the route in global.asax => by default it doesn't allow you to specify any action name => it uses the HTTP verb to dispatch). So when you send a GET request to /api/users/authenticate you are basically calling the Get(int id) action and passing id=authenticate which obviously crashes because your Get action expects an integer.

If you want to have different action names than the standard ones you could modify your route definition in global.asax:

Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { action = "get", id = RouteParameter.Optional }
);

Now you can navigate to /api/users/getauthenticate to authenticate the user.

Read only file system on Android

As chen-xing mentioned the simplest way is:

adb reboot

But for me I had to change my settings first:

Settings ? Developer options ? Root access

Make sure ADB has Root access:

enter image description here

Finding sum of elements in Swift array

A possible solution: define a prefix operator for it. Like the reduce "+/" operator as in APL (e.g. GNU APL)

A bit of a different approach here.

Using a protocol en generic type allows us to to use this operator on Double, Float and Int array types

protocol Number 
{
   func +(l: Self, r: Self) -> Self
   func -(l: Self, r: Self) -> Self
   func >(l: Self, r: Self) -> Bool
   func <(l: Self, r: Self) -> Bool
}

extension Double : Number {}
extension Float  : Number {}
extension Int    : Number {}

infix operator += {}

func += <T:Number> (inout left: T, right: T)
{
   left = left + right
}

prefix operator +/ {}

prefix func +/ <T:Number>(ar:[T]?) -> T?
{
    switch true
    {
    case ar == nil:
        return nil

    case ar!.isEmpty:
        return nil

    default:
        var result = ar![0]
        for n in 1..<ar!.count
        {
            result += ar![n]
        }
        return result
   }
}

use like so:

let nmbrs = [ 12.4, 35.6, 456.65, 43.45 ]
let intarr = [1, 34, 23, 54, 56, -67, 0, 44]

+/nmbrs     // 548.1
+/intarr    // 145

(updated for Swift 2.2, tested in Xcode Version 7.3)

How to find when a web page was last updated

This is a Pythonic way to do it:

import httplib
import yaml
c = httplib.HTTPConnection(address)
c.request('GET', url_path)
r = c.getresponse()
# get the date into a datetime object
lmd = r.getheader('last-modified')
if lmd != None:
   cur_data = { url: datetime.strptime(lmd, '%a, %d %b %Y %H:%M:%S %Z') }
else:
   print "Hmmm, no last-modified data was returned from the URL."
   print "Returned header:"
   print yaml.dump(dict(r.getheaders()), default_flow_style=False)

The rest of the script includes an example of archiving a page and checking for changes against the new version, and alerting someone by email.

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

How can I use a carriage return in a HTML tooltip?

I don't believe it is. Firefox 2 trims long link titles anyway and they should really only be used to convey a small amount of help text. If you need more explanation text I would suggest that it belongs in a paragraph associated with the link. You could then add the tooltip javascript code to hide those paragraphs and show them as tooltips on hover. That's your best bet for getting it to work cross-browser IMO.

What is %2C in a URL?

The %2C translates to a comma (,). I saw this while searching for a sentence with a comma in it and on the url, instead of showing a comma, it had %2C.

Delete commit on gitlab

Supose you have the following scenario:

* 1bd2200 (HEAD, master) another commit
* d258546 bad commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit

Where you want to remove d258546 i.e. "bad commit".

You shall try an interactive rebase to remove it: git rebase -i 34c4f95

then your default editor will pop with something like this:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick d258546 bad commit
 pick 1bd2200 another commit

 # Rebase 34c4f95..1bd2200 onto 34c4f95
 #
 # Commands:
 #  p, pick = use commit
 #  r, reword = use commit, but edit the commit message
 #  e, edit = use commit, but stop for amending
 #  s, squash = use commit, but meld into previous commit
 #  f, fixup = like "squash", but discard this commit's log message
 #  x, exec = run command (the rest of the line) using shell
 #
 # These lines can be re-ordered; they are executed from top to bottom.
 #
 # If you remove a line here THAT COMMIT WILL BE LOST.
 #
 # However, if you remove everything, the rebase will be aborted.
 #
 # Note that empty commits are commented out

just remove the line with the commit you want to strip and save+exit the editor:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick 1bd2200 another commit
 ...

git will proceed to remove this commit from your history leaving something like this (mind the hash change in the commits descendant from the removed commit):

 * 34fa994 (HEAD, master) another commit
 * 0f1efa9 3rd commit
 * bd8aa13 2nd commit
 * 34c4f95 1st commit

Now, since I suppose that you already pushed the bad commit to gitlab, you'll need to repush your graph to the repository (but with the -f option to prevent it from being rejected due to a non fastforwardeable history i.e. git push -f <your remote> <your branch>)

Please be extra careful and make sure that none coworker is already using the history containing the "bad commit" in their branches.

Alternative option:

Instead of rewrite the history, you may simply create a new commit which negates the changes introduced by your bad commit, to do this just type git revert <your bad commit hash>. This option is maybe not as clean, but is far more safe (in case you are not fully aware of what are you doing with an interactive rebase).

Why do I get access denied to data folder when using adb?

This works if your Android device is rooted by any means (not sure if it works for non-rooted).

  1. adb shell - access the shell
  2. su - become the superuser.

You can now read all files in all directories.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

I had met a similar problem, after i add a scope property of servlet dependency in pom.xml

 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Then it was ok . maybe that will help you.

How to use type: "POST" in jsonp ajax call

Here is the JSONP I wrote to share with everyone:

the page to send req
http://c64.tw/r20/eqDiv/fr64.html

please save the srec below to .html youself
c64.tw/r20/eqDiv/src/fr64.txt
the page to resp, please save the srec below to .jsp youself
c64.tw/r20/eqDiv/src/doFr64.txt

or embedded the code in your page:

function callbackForJsonp(resp) {

var elemDivResp = $("#idForDivResp");
elemDivResp.empty();

try {

    elemDivResp.html($("#idForF1").val() + " + " + $("#idForF2").val() + "<br/>");
    elemDivResp.append(" = " + resp.ans + "<br/>");
    elemDivResp.append(" = " + resp.ans2 + "<br/>");

} catch (e) {

    alert("callbackForJsonp=" + e);

}

}

$(document).ready(function() {

var testUrl = "http://c64.tw/r20/eqDiv/doFr64.jsp?callback=?";

$(document.body).prepend("post to " + testUrl + "<br/><br/>");

$("#idForBtnToGo").click(function() {

    $.ajax({

        url : testUrl,
        type : "POST",

        data : {
            f1 : $("#idForF1").val(),
            f2 : $("#idForF2").val(),
            op : "add"
        },

        dataType : "jsonp",
        crossDomain : true,
        //jsonpCallback : "callbackForJsonp",
        success : callbackForJsonp,

        //success : function(resp) {

        //console.log("Yes, you success");
        //callbackForJsonp(resp);

        //},

        error : function(XMLHttpRequest, status, err) {

            console.log(XMLHttpRequest.status + "\n" + err);
            //alert(XMLHttpRequest.status + "\n" + err);

        }

    });

});

});

How to declare a static const char* in your header file?

To answer the OP's question about why it is only allowed with integral types.

When an object is used as an lvalue (i.e. as something that has address in storage), it has to satisfy the "one definition rule" (ODR), i.e it has to be defined in one and only one translation unit. The compiler cannot and will not decide which translation unit to define that object in. This is your responsibility. By defining that object somewhere you are not just defining it, you are actually telling the compiler that you want to define it here, in this specific translation unit.

Meanwhile, in C++ language integral constants have special status. They can form integral constant expressions (ICEs). In ICEs integral constants are used as ordinary values, not as objects (i.e. it is not relevant whether such integral value has address in the storage or not). In fact, ICEs are evaluated at compile time. In order to facilitate such a use of integral constants their values have to be visible globally. And the constant itself don't really need an actual place in the storage. Because of this integral constants received special treatment: it was allowed to include their initializers in the header file, and the requirement to provide a definition was relaxed (first de facto, then de jure).

Other constant types has no such properties. Other constant types are virtually always used as lvalues (or at least can't participate in ICEs or anything similar to ICE), meaning that they require a definition. The rest follows.

UIView touch event in controller

Updating @Crashalot's answer for Swift 3.x:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

SQL Server - transactions roll back on error?

Here the code with getting the error message working with MSSQL Server 2016:

BEGIN TRY
    BEGIN TRANSACTION 
        -- Do your stuff that might fail here
    COMMIT
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN

        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE()
        DECLARE @ErrorSeverity INT = ERROR_SEVERITY()
        DECLARE @ErrorState INT = ERROR_STATE()

    -- Use RAISERROR inside the CATCH block to return error  
    -- information about the original error that caused  
    -- execution to jump to the CATCH block.  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH

Bind a function to Twitter Bootstrap Modal Close

I was having the same issues as some with

$('#myModal').on('hidden.bs.modal', function () {
// do something… })

You need to place this at the bottom of the page, placing it at the top never fires the event.

Sending email through Gmail SMTP server with C#

CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.

Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("[email protected]", "mypwd"),
                EnableSsl = true
            };
            client.Send("[email protected]", "[email protected]", "test", "testbody");
            Console.WriteLine("Sent");
            Console.ReadLine();
        }
    }
}

I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl in the configuration file :( ).

Get File Path (ends with folder)

If you want to browse to a folder by default: For example "D:\Default_Folder" just initialise the "InitialFileName" attribute

Dim diaFolder As FileDialog

' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.InitialFileName = "D:\Default_Folder"
diaFolder.Show

UIGestureRecognizer on UIImageView

Check that userInteractionEnabled is YES on the UIImageView. Then you can add a gesture recognizer.

imageView.userInteractionEnabled = YES;
UIPinchGestureRecognizer *pgr = [[UIPinchGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handlePinch:)];
pgr.delegate = self;
[imageView addGestureRecognizer:pgr];
[pgr release];
:
:
- (void)handlePinch:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
  //handle pinch...
}

XPath using starts-with function

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

Class has no initializers Swift

My answer addresses the error in general and not the exact code of the OP. No answer mentioned this note so I just thought I add it.

The code below would also generate the same error:

class Actor {
    let agent : String? // BAD! // Its value is set to nil, and will always be nil and that's stupid so Xcode is saying not-accepted.  
    // Technically speaking you have a way around it, you can help the compiler and enforce your value as a constant. See Option3
}

Others mentioned that Either you create initializers or you make them optional types, using ! or ? which is correct. However if you have an optional member/property, that optional should be mutable ie var. If you make a let then it would never be able to get out of its nil state. That's bad!

So the correct way of writing it is:

Option1

class Actor {
    var agent : String? // It's defaulted to `nil`, but also has a chance so it later can be set to something different || GOOD!
}

Or you can write it as:

Option2

class Actor {
let agent : String? // It's value isn't set to nil, but has an initializer || GOOD!

init (agent: String?){
    self.agent = agent // it has a chance so its value can be set!
    }
}

or default it to any value (including nil which is kinda stupid)

Option3

class Actor {
let agent : String? = nil // very useless, but doable.
let company: String? = "Universal" 
}

If you are curious as to why let (contrary to var) isn't initialized to nil then read here and here

Determine command line working directory when running node bin script

Alternatively, if you want to solely obtain the current directory of the current NodeJS script, you could try something simple like this. Note that this will not work in the Node CLI itself:

var fs = require('fs'),
    path = require('path');

var dirString = path.dirname(fs.realpathSync(__filename));

// output example: "/Users/jb/workspace/abtest"
console.log('directory to start walking...', dirString);

Change Bootstrap tooltip color

Bootstrap 2

If you want to change the caret/arrow as well, do the following:

.red-tooltip + .tooltip > .tooltip-inner {background-color: #f00;}
.red-tooltip + .tooltip > .tooltip-arrow {border-bottom-color: #f00;}

or

.red-tooltip + .tooltip > .tooltip-inner, .red-tooltip + .tooltip > .tooltip-arrow {background-color: #f00;}

jsFiddle: http://jsfiddle.net/technotarek/2htZe/

UPDATE: Bootstrap 3

You have to be specific for the direction of the tooltip in Bootstrap 3. For example:

.tooltip.top .tooltip-inner {
    background-color:red;
}
.tooltip.top .tooltip-arrow {
      border-top-color: red;
}

jsFiddle for all tooltip directions using Bootstrap 3: http://jsfiddle.net/technotarek/L2rLE/

How to list all Git tags?

Also git show-ref is rather useful, so that you can directly associate tags with correspondent commits:

$ git tag
osgeolive-6.5
v8.0
...

$ git show-ref --tags
e7e66977c1f34be5627a268adb4b9b3d59700e40 refs/tags/osgeolive-6.5
8f27e65bddd7d4b8515ce620fb485fdd78fcdf89 refs/tags/v8.0
...

Hash function for a string

Use boost::hash

#include <boost\functional\hash.hpp>

...

std::string a = "ABCDE";
size_t b = boost::hash_value(a);

python convert list to dictionary

Using the usual grouper recipe, you could do:

Python 2:

d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

Python 3:

d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))

Drop all data in a pandas dataframe

Overwrite the dataframe with something like that

import pandas as pd

df = pd.DataFrame(None)

or if you want to keep columns in place

df = pd.DataFrame(columns=df.columns)

How to determine if binary tree is balanced?

Stumbled across this old question while searching for something else. I notice that you never did get a complete answer.

The way to solve this problem is to start by writing a specification for the function you are trying to write.

Specification: A well-formed binary tree is said to be "height-balanced" if (1) it is empty, or (2) its left and right children are height-balanced and the height of the left tree is within 1 of the height of the right tree.

Now that you have the specification, the code is trivial to write. Just follow the specification:

IsHeightBalanced(tree)
    return (tree is empty) or 
           (IsHeightBalanced(tree.left) and
            IsHeightBalanced(tree.right) and
            abs(Height(tree.left) - Height(tree.right)) <= 1)

Translating that into the programming language of your choice should be trivial.

Bonus exercise: this naive code sketch traverses the tree far too many times when computing the heights. Can you make it more efficient?

Super bonus exercise: suppose the tree is massively unbalanced. Like, a million nodes deep on one side and three deep on the other. Is there a scenario in which this algorithm blows the stack? Can you fix the implementation so that it never blows the stack, even when given a massively unbalanced tree?

UPDATE: Donal Fellows points out in his answer that there are different definitions of 'balanced' that one could choose. For example, one could take a stricter definition of "height balanced", and require that the path length to the nearest empty child is within one of the path to the farthest empty child. My definition is less strict than that, and therefore admits more trees.

One can also be less strict than my definition; one could say that a balanced tree is one in which the maximum path length to an empty tree on each branch differs by no more than two, or three, or some other constant. Or that the maximum path length is some fraction of the minimum path length, like a half or a quarter.

It really doesn't matter usually. The point of any tree-balancing algorithm is to ensure that you do not wind up in the situation where you have a million nodes on one side and three on the other. Donal's definition is fine in theory, but in practice it is a pain coming up with a tree-balancing algorithm that meets that level of strictness. The performance savings usually does not justify the implementation cost. You spend a lot of time doing unnecessary tree rearrangements in order to attain a level of balance that in practice makes little difference. Who cares if sometimes it takes forty branches to get to the farthest leaf in a million-node imperfectly-balanced tree when it could in theory take only twenty in a perfectly balanced tree? The point is that it doesn't ever take a million. Getting from a worst case of a million down to a worst case of forty is usually good enough; you don't have to go all the way to the optimal case.

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

In my case, I used the old namespace library while my project was set up making use of androidx one.

The solution was to replace android.support.design.widget.BottomNavigationView component with the right one to escape from support library: com.google.android.material.bottomnavigation.BottomNavigationView.

How to send data with angularjs $http.delete() request?

$http.delete method doesn't accept request body. You can try this workaround :

$http( angular.merge({}, config || {}, {
    method  : 'delete',
    url     : _url,
    data    : _data
}));

where in config you can pass config data like headers etc.

How do I change the hover over color for a hover over table in Bootstrap?

HTML CODE:

<table class="table table-hover">
    <thead>
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John</td>
            <td>Doe</td>
            <td>[email protected]</td>
        </tr>
        <tr>
            <td>Mary</td>
            <td>Moe</td>
            <td>[email protected]</td>
        </tr>
        <tr>
            <td>July</td>
            <td>Dooley</td>
            <td>[email protected]</td>
        </tr>
    </tbody>

CSS CODE

.table-hover thead tr:hover th, .table-hover tbody tr:hover td {
    background-color: #D1D119;
}

The css code indicate that:

mouse over row:

.table-hover > thead > tr:hover

background color of th will change to #D1D119

th

Same action will happen for tbody

.table-hover tbody tr:hover td

how to POST/Submit an Input Checkbox that is disabled?

create a css class eg:

.disable{
        pointer-events: none;
        opacity: 0.5;
}

apply this class instead of disabled attribute

python for increment inner loop

for a in range(1):

    for b in range(3):
        a = b*2
        print(a)

As per your question, you want to iterate the outer loop with help of the inner loop.

  1. In outer loop, we are iterating the inner loop 1 time.
  2. In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.

    Output:
    0
    2
    4
    

continuing execution after an exception is thrown in java

If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.

try {

    //Dangerous code: could throw an error

} catch (Exception e) {

    //Cleanup: make sure that this methods variables and such are in the desired state

    throw e;
}

This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.

An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.

VBA Excel - Insert row below with same format including borders and frames

The easiest option is to make use of the Excel copy/paste.

Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub

How do I toggle an element's class in pure JavaScript?

Take a look at this example: JS Fiddle

function toggleClass(element, className){
    if (!element || !className){
        return;
    }

    var classString = element.className, nameIndex = classString.indexOf(className);
    if (nameIndex == -1) {
        classString += ' ' + className;
    }
    else {
        classString = classString.substr(0, nameIndex) + classString.substr(nameIndex+className.length);
    }
    element.className = classString;
}

Python method for reading keypress?

from msvcrt import getch

pos = [0, 0]

def fright():
    global pos
    pos[0] += 1

def fleft():
    global pos 
    pos[0] -= 1

def fup():
    global pos
    pos[1] += 1

def fdown():
    global pos
    pos[1] -= 1

while True:
    print'Distance from zero: ', pos
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        print('selected')
    elif key == 32: #Space
        print('jump')
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            print('down')
            fdown
        elif key == 72: #Up arrow
            print('up')
            fup()
        elif key == 75: #Left arrow
            print('left')
            fleft()
        elif key == 77: #Right arrow
            print('right')
            fright()

How can I find the link URL by link text with XPath?

For case insensitive contains, use the following:

//a[contains(translate(text(),'PROGRAMMING','programming'), 'programming')]/@href

translate converts capital letters in PROGRAMMING to lower case programming.

PHP random string generator

There are 3 things wrong with your code:

  1. $randstring is not assigned to anything (only inside the function which is out of scope).
  2. RandomString only returns the last random charactor. Replace = with .=.
  3. Rand does not generate cryptographically secure pseudo-random numbers. Use random_int instead.

See below:

<?php
    function RandomString()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < 10; $i++) {
            $randstring .= $characters[random_int(0, strlen($characters))];
        }
        return $randstring;
    }
    $randstring = RandomString();
    echo $randstring;

How to force a checkbox and text on the same line?

Try this CSS:

label {
  display: inline-block;
}

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

How to make (link)button function as hyperlink?

This can be done very easily using a PostBackUrl and a regular button.

<asp:Button ID="Button1" runat="server" Text="Name of web location" PostBackUrl="web address" />

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

If you would like to ignore case you could use the following:

String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
    //-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
    // strings are equal.
}

print arraylist element?

Here is an updated solution for Java8, using lambdas and streams:

System.out.println(list.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining("\n")));

Or, without joining the list into one large string:

list.stream().forEach(System.out::println);

How to remove all MySQL tables from the command-line without DROP database permissions?

You can drop the database and then recreate it with the below:-

mysql> drop database [database name];
mysql> create database [database name];

How to run a specific Android app using Terminal?

You can Start the android Service by this command.

adb shell am startservice -n packageName/.ServiceClass

How to initialize an array in Kotlin with values?

Worth mentioning that when using kotlin builtines (e.g. intArrayOf(), longArrayOf(), arrayOf(), etc) you are not able to initialize the array with default values (or all values to desired value) for a given size, instead you need to do initialize via calling according to class constructor.

// Array of integers of a size of N
val arr = IntArray(N)

// Array of integers of a size of N initialized with a default value of 2
val arr = IntArray(N) { i -> 2 }

Load HTML File Contents to Div [without the use of iframes]

I'd suggest getting into one of the JS libraries out there. They ensure compatibility so you can get up and running really fast. jQuery and DOJO are both really great. To do what you're trying to do in jQuery, for example, it would go something like this:

<script type="text/javascript" language="JavaScript">
$.ajax({
    url: "x.html", 
    context: document.body,
    success: function(response) {
        $("#yourDiv").html(response);
    }
});
</script>

How to pass html string to webview on android

I was using some buttons with some events, converted image file coming from server. Loading normal data wasn't working for me, converting into Base64 working just fine.

String unencodedHtml ="<html><body>'%28' is the code for '('</body></html>";
tring encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");

Find details on WebView

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

Why does cURL return error "(23) Failed writing body"?

You can do this instead of using -o option:

curl [url] > [file]

Using OR & AND in COUNTIFS

One solution is doing the sum:

=SUM(COUNTIFS(A1:A196,{"yes","no"},B1:B196,"agree"))

or know its not the countifs but the sumproduct will do it in one line:

=SUMPRODUCT(((A1:A196={"yes","no"})*(j1:j196="agree")))

c# dictionary one key many values

As of .net3.5+ instead of using a Dictionary<IKey, List<IValue>> you can use a Lookup from the Linq namespace:

// lookup Order by payment status (1:m) 
// would need something like Dictionary<Boolean, IEnumerable<Order>> orderIdByIsPayed
ILookup<Boolean, Order> byPayment = orderList.ToLookup(o => o.IsPayed);
IEnumerable<Order> payedOrders = byPayment[false];

From msdn:

A Lookup resembles a Dictionary. The difference is that a Dictionary maps keys to single values, whereas a Lookup maps keys to collections of values.

You can create an instance of a Lookup by calling ToLookup on an object that implements IEnumerable.

You may also want to read this answer to a related question. For more info, consult msdn.

Full example:

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqLookupSpike
{
    class Program
    {
        static void Main(String[] args)
        {
            // init 
            var orderList = new List<Order>();
            orderList.Add(new Order(1, 1, 2010, true));//(orderId, customerId, year, isPayed)
            orderList.Add(new Order(2, 2, 2010, true));
            orderList.Add(new Order(3, 1, 2010, true));
            orderList.Add(new Order(4, 2, 2011, true));
            orderList.Add(new Order(5, 2, 2011, false));
            orderList.Add(new Order(6, 1, 2011, true));
            orderList.Add(new Order(7, 3, 2012, false));

            // lookup Order by its id (1:1, so usual dictionary is ok)
            Dictionary<Int32, Order> orders = orderList.ToDictionary(o => o.OrderId, o => o);

            // lookup Order by customer (1:n) 
            // would need something like Dictionary<Int32, IEnumerable<Order>> orderIdByCustomer
            ILookup<Int32, Order> byCustomerId = orderList.ToLookup(o => o.CustomerId);
            foreach (var customerOrders in byCustomerId)
            {
                Console.WriteLine("Customer {0} ordered:", customerOrders.Key);
                foreach (var order in customerOrders)
                {
                    Console.WriteLine("    Order {0} is payed: {1}", order.OrderId, order.IsPayed);
                }
            }

            // the same using old fashioned Dictionary
            Dictionary<Int32, List<Order>> orderIdByCustomer;
            orderIdByCustomer = byCustomerId.ToDictionary(g => g.Key, g => g.ToList());
            foreach (var customerOrders in orderIdByCustomer)
            {
                Console.WriteLine("Customer {0} ordered:", customerOrders.Key);
                foreach (var order in customerOrders.Value)
                {
                    Console.WriteLine("    Order {0} is payed: {1}", order.OrderId, order.IsPayed);
                }
            }

            // lookup Order by payment status (1:m) 
            // would need something like Dictionary<Boolean, IEnumerable<Order>> orderIdByIsPayed
            ILookup<Boolean, Order> byPayment = orderList.ToLookup(o => o.IsPayed);
            IEnumerable<Order> payedOrders = byPayment[false];
            foreach (var payedOrder in payedOrders)
            {
                Console.WriteLine("Order {0} from Customer {1} is not payed.", payedOrder.OrderId, payedOrder.CustomerId);
            }
        }

        class Order
        {
            // key properties
            public Int32 OrderId { get; private set; }
            public Int32 CustomerId { get; private set; }
            public Int32 Year { get; private set; }
            public Boolean IsPayed { get; private set; }

            // additional properties
            // private List<OrderItem> _items;

            public Order(Int32 orderId, Int32 customerId, Int32 year, Boolean isPayed)
            {
                OrderId = orderId;
                CustomerId = customerId;
                Year = year;
                IsPayed = isPayed;
            }
        }
    }
}

Remark on Immutability

By default, Lookups are kind of immutable and accessing the internals would involve reflection. If you need mutability and don't want to write your own wrapper, you could use MultiValueDictionary (formerly known as MultiDictionary) from corefxlab (formerly part ofMicrosoft.Experimental.Collections which isn't updated anymore).

Java RegEx meta character (.) and ordinary dot?

If you want the dot or other characters with a special meaning in regexes to be a normal character, you have to escape it with a backslash. Since regexes in Java are normal Java strings, you need to escape the backslash itself, so you need two backslashes e.g. \\.

Where to find Application Loader app in Mac?

I have found in following way :

Go to https://itunesconnect.apple.com/ , sign in

Click "Resources and Help"

enter image description here

enter image description here

Calculate the mean by group

2015 update with dplyr:

df %>% group_by(dive) %>% summarise(percentage = mean(speed))
Source: local data frame [2 x 2]

   dive percentage
1 dive1  0.4777462
2 dive2  0.6726483

Implement a loading indicator for a jQuery AJAX call

A loading indicator is simply an animated image (.gif) that is displayed until the completed event is called on the AJAX request. http://ajaxload.info/ offers many options for generating loading images that you can overlay on your modals. To my knowledge, Bootstrap does not provide the functionality built-in.

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

Buttons with the btn class do not have underlines unless you are doing something wrong: In this case nesting <button> inside of <a>.

Something that I think you might be trying to do, is to create a bootstrap button without any decorations (underline, outline, button borders, etc). In other words, if your anchor is not a hyperlink, it is semantically a button.

Bootstrap's existing btn class appears to be the correct way to remove underline decorations from anchor buttons:

Use the button classes on an <a>, <button>, or <input> element

EDIT: Hitesh points out that btn will give you a shadow on :active. Thanks! I have modified my first example to use btn-link and incorporated the accepted answer's text-decoration: none to avoid this problem. Note that nesting a button inside of an anchor remains malformed html, a point which isn't addressed by any of the other answers.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div>_x000D_
    <!-- use anchors for borderless buttons -->_x000D_
    <a href="#" class="btn btn-link" style="text-decoration: none">Text</a> _x000D_
    <a href="#" class="btn btn-link" style="text-decoration: none">Text</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Alternatively, for a regular button group using anchors:

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="btn-group">_x000D_
    <!-- use anchors for borderless buttons -->_x000D_
    <a href="#" class="btn btn-default">Text</a> _x000D_
    <a href="#" class="btn btn-default">Text</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In other words, it should not be necessary to introduce your own nounderline class and/or custom styling as the other answers suggest. However, be aware of certain subtleties.


According to the HTML5 spec, <a><button>..</button></a> is illegal:

Content model: Transparent, but there must be no interactive content descendant.

...

Interactive content is content that is specifically intended for user interaction. a, audio (if the controls attribute is present), button, embed, iframe, img (if the usemap attribute is present), input (if the type attribute is not in the hidden state), keygen, label, object (if the usemap attribute is present), select, textarea, video (if the controls attribute is present)


P.S. If, conversely, you wanted a button that has underline decorations, you might have used btn-link. However, that should be rare - this is almost always just an anchor instead of a button!

Why dividing two integers doesn't get a float?

Chapter and verse

6.5.5 Multiplicative operators
...
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.105) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is unde?ned.

105) This is often called ‘‘truncation toward zero’’.

Dividing an integer by an integer gives an integer result. 1/2 yields 0; assigning this result to a floating-point variable gives 0.0. To get a floating-point result, at least one of the operands must be a floating-point type. b = a / 350.0f; should give you the result you want.

Xcopy Command excluding files and folders

Just give full path to exclusion file: eg..

-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt

In this example the file would be located " C:\list-of-excluded-files.txt "

or...

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt

In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "

Full path fixes syntax error.

Calling the base class constructor from the derived class constructor

First off, a PetStore is not a farm.

Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:

Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);

These are the methods you're given access to and these are the ones you should use.

I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ??

Simple, you call addAnimal. It's public and it also increments sizeF.

Also, note that

PetStore()
{
 idF=0;
};

is equivalent to

PetStore() : Farm()
{
 idF=0;
};

i.e. the base constructor is called, base members are initialized.

Is there a “not in” operator in JavaScript for checking object properties?

It seems wrong to me to set up an if/else statement just to use the else portion...

Just negate your condition, and you'll get the else logic inside the if:

if (!(id in tutorTimes)) { ... }

Quoting backslashes in Python string literals

If you are here for a filepath just use "\\"

import os
path = r"c:\file"+"\\"+"path"
os.path.normpath(path)

which will outputc:\file\path

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

Make sure you're calling super() as the first thing in your constructor.

You should set this for setAuthorState method

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  constructor(props) {
    super(props);
    this.handleAuthorChange = this.handleAuthorChange.bind(this);
  } 

  handleAuthorChange(event) {
    let {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

Another alternative based on arrow function:

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  handleAuthorChange = (event) => {
    const {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

Permission denied for relation

Make sure you log into psql as the owner of the tables. to find out who own the tables use \dt

psql -h CONNECTION_STRING DBNAME -U OWNER_OF_THE_TABLES

then you can run the GRANTS

sed: print only matching group

grep is the right tool for extracting.

using your example and your regex:

kent$  echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4

How to set the color of an icon in Angular Material?

<mat-icon style="-webkit-text-fill-color:blue">face</mat-icon>

How to append text to an existing file in Java?

This code will fulifil your need:

   FileWriter fw=new FileWriter("C:\\file.json",true);
   fw.write("ssssss");
   fw.close();

How to set cellpadding and cellspacing in table with CSS?

The padding inside a table-divider (TD) is a padding property applied to the cell itself.

CSS

td, th {padding:0}

The spacing in-between the table-dividers is a space between cell borders of the TABLE. To make it effective, you have to specify if your table cells borders will 'collapse' or be 'separated'.

CSS

table, td, th {border-collapse:separate}
table {border-spacing:6px}

Try this : https://www.google.ca/search?num=100&newwindow=1&q=css+table+cellspacing+cellpadding+site%3Astackoverflow.com ( 27 100 results )

How to detect a docker daemon port

  1. Prepare extra configuration file. Create a file named /etc/systemd/system/docker.service.d/docker.conf. Inside the file docker.conf, paste below content:
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock

Note that if there is no directory like docker.service.d or a file named docker.conf then you should create it.

  1. Restart Docker. After saving this file, reload the configuration by systemctl daemon-reload and restart Docker by systemctl restart docker.service.

  2. Check your Docker daemon. After restarting docker service, you can see the port in the output of systemctl status docker.service like /usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock.

Hope this may help

Thank you!

Installing a pip package from within a Jupyter Notebook not working

Try using some shell magic: %%sh %%sh pip install geocoder let me know if it works, thanks

How can I add a Google search box to my website?

This is one of the way to add google site search to websites:

_x000D_
_x000D_
<form action="https://www.google.com/search" class="searchform" method="get" name="searchform" target="_blank">_x000D_
<input name="sitesearch" type="hidden" value="example.com">_x000D_
<input autocomplete="on" class="form-control search" name="q" placeholder="Search in example.com" required="required"  type="text">_x000D_
<button class="button" type="submit">Search</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Replace tabs with spaces in vim

If you want to keep your \t equal to 8 spaces then consider setting:

   set softtabstop=2 tabstop=8 shiftwidth=2

This will give you two spaces per <TAB> press, but actual \t in your code will still be viewed as 8 characters.

jquery select option click handler

The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.

I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:

let blockChange = false;

$element.keydown(function (e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);

    // prevents select opening when enter is pressed
    if (keycode === 13) {
        e.preventDefault();
    }

    // lets the change event know that these keypresses are to be ignored
    if([38, 40].indexOf(keycode) > -1){
        blockChange = true;
    }

});

$element.keyup(function(e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);
    // handle enter press
    if(keycode === 13) {
        doSomething();
    }

});

$element.change(function(e) {

    // this effective handles the click only as preventDefault was used on enter
    if(!blockChange) {
        doSomething();
    }
    blockChange = false;

});

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

The best way to handle the LazyInitializationException is to use the JOIN FETCH directive:

Query query = session.createQuery("""
    select m
    from Model m
    join fetch m.modelType
    where modelGroup.id = :modelGroupId
    """
);

Anyway, DO NOT use the following Anti-Patterns as suggested by some of the answers:

Sometimes, a DTO projection is a better choice than fetching entities, and this way, you won't get any LazyInitializationException.

Escaping a forward slash in a regular expression

Use the backslash \ or choose a different delimiter, ie m#.\d# instead of /.\d/ "In Perl, you can change the / regular expression delimiter to almost any other special character if you preceed it with the letter m (for match);"

How do I "decompile" Java class files?

Update February 2016:

www.javadecompilers.com lists JAD as being:

the most popular Java decompiler, but primarily of this age only. Written in C++, so very fast.
Outdated, unsupported and does not decompile correctly Java 5 and later

So your mileage may vary with recent jdk (7, 8).

The same site list other tools.

And javadecompiler, as noted by Salvador Valencia in the comments (Sept 2017), offers a SaaS where you upload the .class file to the cloud and it returns you the decompiled code.


Original answer: Oct. 2008

  • The final release of JSR 176, defining the major features of J2SE 5.0 (Java SE 5), has been published on September 30, 2004.
  • The lastest Java version supported by JAD, the famous Java decompiler written by Mr. Pavel Kouznetsov, is JDK 1.3.
  • Most of the Java decompilers downloadable today from the Internet, such as “DJ Java Decompiler” or “Cavaj Java Decompiler”, are powered by JAD: they can not display Java 5 sources.

Java Decompiler (Yet another Fast Java decompiler) has:

  • Explicit support for decompiling and analyzing Java 5+ “.class” files.
  • A nice GUI:

screenshot

It works with compilers from JDK 1.1.8 up to JDK 1.7.0, and others (Jikes, JRockit, etc.).

It features an online live demo version that is actually fully functional! You can just drop a jar file on the page and see the decompiled source code without installing anything.

django no such table:

You can try this!

python manage.py migrate --run-syncdb

I have the same problem with Django 1.9 and 1.10. This code works!

Vim delete blank lines

Found it, it's:

g/^\s*$/d

Source: Power of g at vim wikia

Brief explanation of :g

:[range]g/pattern/cmd

This acts on the specified [range] (default whole file), by executing the Ex command cmd for each line matching pattern (an Ex command is one starting with a colon such as :d for delete). Before executing cmd, "." is set to the current line.

Eclipse doesn't stop at breakpoints

I suddenly experienced the skipping of breakpoints as well in Eclipse Juno CDT. For me the issue was that I had set optimization levels up. Once I set it back to none it was working fine. To set optimization levels go to Project Properties -> C/C++ Build -> Settings -> Tool Settings pan depending on which compiler you are using go to -> Optimization and set Optimization Level to: None (-O0). Hope this helps! Best

Python Timezone conversion

For Python 3.2+ simple-date is a wrapper around pytz that tries to simplify things.

If you have a time then

SimpleDate(time).convert(tz="...")

may do what you want. But timezones are quite complex things, so it can get significantly more complicated - see the the docs.

How to play ringtone/alarm sound in Android

Your example is basically what I'm using. It never works on the emulator, however, because the emulator doesn't have any ringtones by default, and content://settings/system/ringtone doesn't resolve to anything playable. It works fine on my actual phone.

What is the difference between an expression and a statement in Python?

Python calls expressions "expression statements", so the question is perhaps not fully formed.

A statement consists of pretty much anything you can do in Python: calculating a value, assigning a value, deleting a variable, printing a value, returning from a function, raising an exception, etc. The full list is here: http://docs.python.org/reference/simple_stmts.html#

An expression statement is limited to calling functions (e.g., math.cos(theta)"), operators ( e.g., "2+3"), etc. to produce a value.

OSX - How to auto Close Terminal window after the "exit" command executed.

I 've been using ctrl + d. It throws you out into the destination where You've started the sqlite3 command in the first place.

How To Set A JS object property name from a variable

This is the way to dynamically set the value

var jsonVariable = {};
for (var i = 1; i < 3; i++) {
    var jsonKey = i + 'name';
    jsonVariable[jsonKey] = 'name' + i;
}

Random date in C#

Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).

Removing the title text of an iOS UIBarButtonItem

I couldn't get it to work using Guto Araujo's answer of navigationBar.topItem.title = @"";

However, I was able to get the desired effect by setting self.title = @"" in the init method of my view controller. (Setting it in init is important, viewDidLoad won't work.)

When to use a View instead of a Table?

According to Wikipedia,

Views can provide many advantages over tables:

  • Views can represent a subset of the data contained in a table.
  • Views can limit the degree of exposure of the underlying tables to the outer world: a given user may have permission to query the view, while denied access to the rest of the base table.

  • Views can join and simplify multiple tables into a single virtual table.

  • Views can act as aggregated tables, where the database engine aggregates data (sum, average, etc.) and presents the calculated results as part of the data.

  • Views can hide the complexity of data. For example, a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table.

  • Views take very little space to store; the database contains only the definition of a view, not a copy of all the data that it presents.

  • Views can provide extra security, depending on the SQL engine used.

Opening the Settings app from another app

Seems like you can use the prefs:<area> URL to open the settings and go to specific areas. Apple could change these and break your app so always check if you can open them first.

From this article they have listed some of them for iOS 13.1:

Settings URLs

iCloud

  • iCloud: prefs:root=CASTLE
  • iCloud Backup: prefs:root=CASTLE&path=BACKUP

Wireless Radios

  • Wi-Fi: prefs:root=WIFI
  • Bluetooth: prefs:root=Bluetooth
  • Cellular: prefs:root=MOBILE_DATA_SETTINGS_ID

Personal Hotspot

  • Personal Hotspot: prefs:root=INTERNET_TETHERING
  • Personal Hotspot ? Family Sharing: prefs:root=INTERNET_TETHERING&path=Family%20Sharing
  • Personal Hotspot ? Wi-Fi Password: prefs:root=INTERNET_TETHERING&path=Wi-Fi%20Password

VPN

  • VPN: prefs:root=General&path=VPN

Notifications

  • Notifications: prefs:root=NOTIFICATIONS_ID
  • Notifications ? Siri Suggestions: prefs:root=NOTIFICATIONS_ID&path=Siri%20Suggestions

Sounds

  • Sounds: prefs:root=Sounds
  • Ringtone: prefs:root=Sounds&path=Ringtone

Do Not Disturb

  • Do Not Disturb: prefs:root=DO_NOT_DISTURB
  • Do Not Disturb ? Allow Calls From: prefs:root=DO_NOT_DISTURB&path=Allow%20Calls%20From

Screen Time

  • Screen Time: prefs:root=SCREEN_TIME
  • Screen Time ? Downtime: prefs:root=SCREEN_TIME&path=DOWNTIME
  • Screen Time ? App Limits: prefs:root=SCREEN_TIME&path=APP_LIMITS
  • Screen Time ? Always Allowed: prefs:root=SCREEN_TIME&path=ALWAYS_ALLOWED

General

  • General: prefs:root=General
  • General ? About: prefs:root=General&path=About
  • General ? Software Update: prefs:root=General&path=SOFTWARE_UPDATE_LINK
  • General ? CarPlay: prefs:root=General&path=CARPLAY
  • General ? Background App Refresh: prefs:root=General&path=AUTO_CONTENT_DOWNLOAD
  • General ? Multitasking (iPad-only): prefs:root=General&path=MULTITASKING
  • General ? Date & Time: prefs:root=General&path=DATE_AND_TIME
  • General ? Keyboard: prefs:root=General&path=Keyboard
  • General ? Keyboard ? Keyboards: prefs:root=General&path=Keyboard/KEYBOARDS
  • General ? Keyboard ? Hardware Keyboard: prefs:root=General&path=Keyboard/Hardware%20Keyboard
  • General ? Keyboard ? Text Replacement: prefs:root=General&path=Keyboard/USER_DICTIONARY
  • General ? Keyboard ? One Handed Keyboard: prefs:root=General&path=Keyboard/ReachableKeyboard
  • General ? Language & Region: prefs:root=General&path=INTERNATIONAL
  • General ? Dictionary: prefs:root=General&path=DICTIONARY
  • General ? Profiles: prefs:root=General&path=ManagedConfigurationList
  • General ? Reset: prefs:root=General&path=Reset

Control Center

  • Control Center: prefs:root=ControlCenter
  • Control Center ? Customize Controls: prefs:root=ControlCenter&path=CUSTOMIZE_CONTROLS

Display

  • Display: prefs:root=DISPLAY
  • Display ? Auto Lock: prefs:root=DISPLAY&path=AUTOLOCK
  • Display ? Text Size: prefs:root=DISPLAY&path=TEXT_SIZE

Accessibility

  • Accessibility: prefs:root=ACCESSIBILITY

Wallpaper

  • Wallpaper: prefs:root=Wallpaper

Siri

  • Siri: prefs:root=SIRI

Apple Pencil

  • Apple Pencil (iPad-only): prefs:root=Pencil

Face ID

  • Face ID: prefs:root=PASSCODE

Emergency SOS

  • Emergency SOS: prefs:root=EMERGENCY_SOS

Battery

  • Battery: prefs:root=BATTERY_USAGE
  • Battery ? Battery Health (iPhone-only): prefs:root=BATTERY_USAGE&path=BATTERY_HEALTH

Privacy

  • Privacy: prefs:root=Privacy
  • Privacy ? Location Services: prefs:root=Privacy&path=LOCATION
  • Privacy ? Contacts: prefs:root=Privacy&path=CONTACTS
  • Privacy ? Calendars: prefs:root=Privacy&path=CALENDARS
  • Privacy ? Reminders: prefs:root=Privacy&path=REMINDERS
  • Privacy ? Photos: prefs:root=Privacy&path=PHOTOS
  • Privacy ? Microphone: prefs:root=Privacy&path=MICROPHONE
  • Privacy ? Speech Recognition: prefs:root=Privacy&path=SPEECH_RECOGNITION
  • Privacy ? Camera: prefs:root=Privacy&path=CAMERA
  • Privacy ? Motion: prefs:root=Privacy&path=MOTION\

App Store

  • App Store: prefs:root=STORE
  • App Store ? App Downloads: prefs:root=STORE&path=App%20Downloads
  • App Store ? Video Autoplay: prefs:root=STORE&path=Video%20Autoplay

Wallet

  • Wallet: prefs:root=PASSBOOK

Passwords & Accounts

  • Passwords & Accounts: prefs:root=ACCOUNTS_AND_PASSWORDS
  • Passwords & Accounts ? Fetch New Data: prefs:root=ACCOUNTS_AND_PASSWORDS&path=FETCH_NEW_DATA
  • Passwords & Accounts ? Add Account: prefs:root=ACCOUNTS_AND_PASSWORDS&path=ADD_ACCOUNT

Mail

  • Mail: prefs:root=MAIL
  • Mail ? Preview: prefs:root=MAIL&path=Preview
  • Mail ? Swipe Options: prefs:root=MAIL&path=Swipe%20Options
  • Mail ? Notifications: prefs:root=MAIL&path=NOTIFICATIONS
  • Mail ? Blocked: prefs:root=MAIL&path=Blocked
  • Mail ? Muted Thread Action: prefs:root=MAIL&path=Muted%20Thread%20Action
  • Mail ? Blocked Sender Options: prefs:root=MAIL&path=Blocked%20Sender%20Options
  • Mail ? Mark Addresses: prefs:root=MAIL&path=Mark%20Addresses
  • Mail ? Increase Quote Level: prefs:root=MAIL&path=Increase%20Quote%20Level
  • Mail ? Include Attachments with Replies: prefs:root=MAIL&path=Include%20Attachments%20with%20Replies
  • Mail ? Signature: prefs:root=MAIL&path=Signature
  • Mail ? Default Account: prefs:root=MAIL&path=Default%20Account

Contacts

  • Contacts: prefs:root=CONTACTS

Calendar

  • Calendar: prefs:root=CALENDAR
  • Calendar ? Alternate Calendars: prefs:root=CALENDAR&path=Alternate%20Calendars
  • Calendar ? Sync: prefs:root=CALENDAR&path=Sync
  • Calendar ? Default Alert Times: prefs:root=CALENDAR&path=Default%20Alert%20Times
  • Calendar ? Default Calendar: prefs:root=CALENDAR&path=Default%20Calendar

Notes

  • Notes: prefs:root=NOTES
  • Notes ? Default Account: prefs:root=NOTES&path=Default%20Account
  • Notes ? Password: prefs:root=NOTES&path=Password
  • Notes ? Sort Notes By: prefs:root=NOTES&path=Sort%20Notes%20By
  • Notes ? New Notes Start With: prefs:root=NOTES&path=New%20Notes%20Start%20With
  • Notes ? Sort Checked Items: prefs:root=NOTES&path=Sort%20Checked%20Items
  • Notes ? Lines & Grids: prefs:root=NOTES&path=Lines%20%26%20Grids
  • Notes ? Access Notes from Lock Screen: prefs:root=NOTES&path=Access%20Notes%20from%20Lock%20Screen

Reminders

  • Reminders: prefs:root=REMINDERS
  • Reminders ? Default List: prefs:root=REMINDERS&path=DEFAULT_LIST

Voice Memos

  • Voice Memos: prefs:root=VOICE_MEMOS

Phone

  • Phone: prefs:root=Phone

Messages

  • Messages: prefs:root=MESSAGES

FaceTime

  • FaceTime: prefs:root=FACETIME

Maps

  • Maps: prefs:root=MAPS
  • Maps ? Driving & Navigation: prefs:root=MAPS&path=Driving%20%26%20Navigation
  • Maps ? Transit: prefs:root=MAPS&path=Transit

Compass

  • Compass: prefs:root=COMPASS

Measure

  • Measure: prefs:root=MEASURE

Safari

  • Safari: prefs:root=SAFARI
  • Safari ? Content Blockers: prefs:root=SAFARI&path=Content%20Blockers
  • Safari ? Downloads: prefs:root=SAFARI&path=DOWNLOADS
  • Safari ? Close Tabs: prefs:root=SAFARI&path=Close%20Tabs
  • Safari ? Clear History and Data: prefs:root=SAFARI&path=CLEAR_HISTORY_AND_DATA
  • Safari ? Page Zoom: prefs:root=SAFARI&path=Page%20Zoom
  • Safari ? Request Desktop Website: prefs:root=SAFARI&path=Request%20Desktop%20Website
  • Safari ? Reader: prefs:root=SAFARI&path=Reader
  • Safari ? Camera: prefs:root=SAFARI&path=Camera
  • Safari ? Microphone: prefs:root=SAFARI&path=Microphone
  • Safari ? Location: prefs:root=SAFARI&path=Location
  • Safari ? Advanced: prefs:root=SAFARI&path=ADVANCED

News

  • News: prefs:root=NEWS

Health

  • Health: prefs:root=HEALTH

Shortcuts

  • Shortcuts: prefs:root=SHORTCUTS

Music

  • Music: prefs:root=MUSIC
  • Music ? Cellular Data: prefs:root=MUSIC&path=com.apple.Music:CellularData
  • Music ? Optimize Storage: prefs:root=MUSIC&path=com.apple.Music:OptimizeStorage
  • Music ? EQ: prefs:root=MUSIC&path=com.apple.Music:EQ
  • Music ? Volume Limit: prefs:root=MUSIC&path=com.apple.Music:VolumeLimit

TV

  • Settings ? TV: prefs:root=TVAPP

Photos

  • Photos: prefs:root=Photos

Camera

  • Camera: prefs:root=CAMERA
  • Camera ? Record Video: prefs:root=CAMERA&path=Record%20Video
  • Camera ? Record Slo-mo: prefs:root=CAMERA&path=Record%20Slo-mo

Books

  • Books: prefs:root=IBOOKS

Game Center

  • Game Center: prefs:root=GAMECENTER

Return char[]/string from a function

If you want to return a char* from a function, make sure you malloc() it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.

change it to

char* createStr() {
    char char1= 'm';
    char char2= 'y';
    char *str = malloc(3 * sizeof(char));
    if(str == NULL) return NULL;
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';
    return str;
}

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

The Function adds gaussian , salt-pepper , poisson and speckle noise in an image

Parameters
----------
image : ndarray
    Input image data. Will be converted to float.
mode : str
    One of the following strings, selecting the type of noise to add:

    'gauss'     Gaussian-distributed additive noise.
    'poisson'   Poisson-distributed noise generated from the data.
    's&p'       Replaces random pixels with 0 or 1.
    'speckle'   Multiplicative noise using out = image + n*image,where
                n is uniform noise with specified mean & variance.


import numpy as np
import os
import cv2
def noisy(noise_typ,image):
   if noise_typ == "gauss":
      row,col,ch= image.shape
      mean = 0
      var = 0.1
      sigma = var**0.5
      gauss = np.random.normal(mean,sigma,(row,col,ch))
      gauss = gauss.reshape(row,col,ch)
      noisy = image + gauss
      return noisy
   elif noise_typ == "s&p":
      row,col,ch = image.shape
      s_vs_p = 0.5
      amount = 0.004
      out = np.copy(image)
      # Salt mode
      num_salt = np.ceil(amount * image.size * s_vs_p)
      coords = [np.random.randint(0, i - 1, int(num_salt))
              for i in image.shape]
      out[coords] = 1

      # Pepper mode
      num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
      coords = [np.random.randint(0, i - 1, int(num_pepper))
              for i in image.shape]
      out[coords] = 0
      return out
  elif noise_typ == "poisson":
      vals = len(np.unique(image))
      vals = 2 ** np.ceil(np.log2(vals))
      noisy = np.random.poisson(image * vals) / float(vals)
      return noisy
  elif noise_typ =="speckle":
      row,col,ch = image.shape
      gauss = np.random.randn(row,col,ch)
      gauss = gauss.reshape(row,col,ch)        
      noisy = image + image * gauss
      return noisy

Remove file extension from a file name string

    /// <summary>
    /// Get the extension from the given filename
    /// </summary>
    /// <param name="fileName">the given filename ie:abc.123.txt</param>
    /// <returns>the extension ie:txt</returns>
    public static string GetFileExtension(this string fileName)
    {
        string ext = string.Empty;
        int fileExtPos = fileName.LastIndexOf(".", StringComparison.Ordinal);
        if (fileExtPos >= 0)
            ext = fileName.Substring(fileExtPos, fileName.Length - fileExtPos);

        return ext;
    }

Difference between volatile and synchronized in Java

tl;dr:

There are 3 main issues with multithreading:

1) Race Conditions

2) Caching / stale memory

3) Complier and CPU optimisations

volatile can solve 2 & 3, but can't solve 1. synchronized/explicit locks can solve 1, 2 & 3.

Elaboration:

1) Consider this thread unsafe code:

x++;

While it may look like one operation, it's actually 3: reading the current value of x from memory, adding 1 to it, and saving it back to memory. If few threads try to do it at the same time, the result of the operation is undefined. If x originally was 1, after 2 threads operating the code it may be 2 and it may be 3, depending on which thread completed which part of the operation before control was transferred to the other thread. This is a form of race condition.

Using synchronized on a block of code makes it atomic - meaning it make it as if the 3 operations happen at once, and there's no way for another thread to come in the middle and interfere. So if x was 1, and 2 threads try to preform x++ we know in the end it will be equal to 3. So it solves the race condition problem.

synchronized (this) {
   x++; // no problem now
}

Marking x as volatile does not make x++; atomic, so it doesn't solve this problem.

2) In addition, threads have their own context - i.e. they can cache values from main memory. That means that a few threads can have copies of a variable, but they operate on their working copy without sharing the new state of the variable among other threads.

Consider that on one thread, x = 10;. And somewhat later, in another thread, x = 20;. The change in value of x might not appear in the first thread, because the other thread has saved the new value to its working memory, but hasn't copied it to the main memory. Or that it did copy it to the main memory, but the first thread hasn't updated its working copy. So if now the first thread checks if (x == 20) the answer will be false.

Marking a variable as volatile basically tells all threads to do read and write operations on main memory only. synchronized tells every thread to go update their value from main memory when they enter the block, and flush the result back to main memory when they exit the block.

Note that unlike data races, stale memory is not so easy to (re)produce, as flushes to main memory occur anyway.

3) The complier and CPU can (without any form of synchronization between threads) treat all code as single threaded. Meaning it can look at some code, that is very meaningful in a multithreading aspect, and treat it as if it’s single threaded, where it’s not so meaningful. So it can look at a code and decide, in sake of optimisation, to reorder it, or even remove parts of it completely, if it doesn’t know that this code is designed to work on multiple threads.

Consider the following code:

boolean b = false;
int x = 10;

void threadA() {
    x = 20;
    b = true;
}

void threadB() {
    if (b) {
        System.out.println(x);
    }
}

You would think that threadB could only print 20 (or not print anything at all if threadB if-check is executed before setting b to true), as b is set to true only after x is set to 20, but the compiler/CPU might decide to reorder threadA, in that case threadB could also print 10. Marking b as volatile ensures that it won’t be reordered (or discarded in certain cases). Which mean threadB could only print 20 (or nothing at all). Marking the methods as syncrhonized will achieve the same result. Also marking a variable as volatile only ensures that it won’t get reordered, but everything before/after it can still be reordered, so synchronization can be more suited in some scenarios.

Note that before Java 5 New Memory Model, volatile didn’t solve this issue.

Appending to an empty DataFrame in Pandas?

And if you want to add a row, you can use a dictionary:

df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)

which gives you:

   age  height name
0    9       2  Zed

Remove the complete styling of an HTML button/submit

I think it's the button "active" state.

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

Use header to modify the HTTP header:

header('Content-Type: text/html; charset=utf-8');

Note to call this function before any output has been sent to the client. Otherwise the header has been sent too and you obviously can’t change it any more. You can check that with headers_sent. See the manual page of header for more information.

What is the difference between a heuristic and an algorithm?

An algorithm is a self-contained step-by-step set of operations to be performed 4, typically interpreted as a finite sequence of (computer or human) instructions to determine a solution to a problem such as: is there a path from A to B, or what is the smallest path between A and B. In the latter case, you could also be satisfied with a 'reasonably close' alternative solution.

There are certain categories of algorithms, of which the heuristic algorithm is one. Depending on the (proven) properties of the algorithm in this case, it falls into one of these three categories (note 1):

  • Exact: the solution is proven to be an optimal (or exact solution) to the input problem
  • Approximation: the deviation of the solution value is proven to be never further away from the optimal value than some pre-defined bound (for example, never more than 50% larger than the optimal value)
  • Heuristic: the algorithm has not been proven to be optimal, nor within a pre-defined bound of the optimal solution

Notice that an approximation algorithm is also a heuristic, but with the stronger property that there is a proven bound to the solution (value) it outputs.

For some problems, noone has ever found an 'efficient' algorithm to compute the optimal solutions (note 2). One of those problems is the well-known Traveling Salesman Problem. Christophides' algorithm for the Traveling Salesman Problem, for example, used to be called a heuristic, as it was not proven that it was within 50% of the optimal solution. Since it has been proven, however, Christophides' algorithm is more accurately referred to as an approximation algorithm.

Due to restrictions on what computers can do, it is not always possible to efficiently find the best solution possible. If there is enough structure in a problem, there may be an efficient way to traverse the solution space, even though the solution space is huge (i.e. in the shortest path problem).

Heuristics are typically applied to improve the running time of algorithms, by adding 'expert information' or 'educated guesses' to guide the search direction. In practice, a heuristic may also be a sub-routine for an optimal algorithm, to determine where to look first.

(note 1): Additionally, algorithms are characterised by whether they include random or non-deterministic elements. An algorithm that always executes the same way and produces the same answer, is called deterministic.

(note 2): This is called the P vs NP problem, and problems that are classified as NP-complete and NP-hard are unlikely to have an 'efficient' algorithm. Note; as @Kriss mentioned in the comments, there are even 'worse' types of problems, which may need exponential time or space to compute.

There are several answers that answer part of the question. I deemed them less complete and not accurate enough, and decided not to edit the accepted answer made by @Kriss

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

Fragment transaction animation: slide in and slide out

There is three way to transaction animation in fragment.

Transitions

So need to use one of the built-in Transitions, use the setTranstion() method:

getSupportFragmentManager()
        .beginTransaction()
        .setTransition( FragmentTransaction.TRANSIT_FRAGMENT_OPEN )
        .show( m_topFragment )
        .commit()

Custom Animations

You can also customize the animation by using the setCustomAnimations() method:

getSupportFragmentManager()
        .beginTransaction()
        .setCustomAnimations( R.anim.slide_up, 0, 0, R.anim.slide_down)
        .show( m_topFragment )
        .commit()

slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:propertyName="translationY"
        android:valueType="floatType"
        android:valueFrom="1280"
        android:valueTo="0"
        android:duration="@android:integer/config_mediumAnimTime"/>

slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:propertyName="translationY"
        android:valueType="floatType"
        android:valueFrom="0"
        android:valueTo="1280"
        android:duration="@android:integer/config_mediumAnimTime"/>

Multiple Animations

Finally, It's also possible to kick-off multiple fragment animations in a single transaction. This allows for a pretty cool effect where one fragment is sliding up and the other slides down at the same time:

getSupportFragmentManager()
        .beginTransaction()
        .setCustomAnimations( R.anim.abc_slide_in_top, R.anim.abc_slide_out_top ) // Top Fragment Animation
        .show( m_topFragment )
        .setCustomAnimations( R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_bottom ) // Bottom Fragment Animation
        .show( m_bottomFragment )
        .commit()

To more detail you can visit URL

Note:- You can check animation according to your requirement because above may be have issue.

What's a .sh file?

sh files are unix (linux) shell executables files, they are the equivalent (but much more powerful) of bat files on windows.

So you need to run it from a linux console, just typing its name the same you do with bat files on windows.

Getting an option text/value with JavaScript

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

How do I extract value from Json

If you don't mind adding a dependency, you can use JsonPath.

import com.jayway.jsonpath.JsonPath;

String firstName = JsonPath.read(rawJsonString, "$.detail.first_name");

"$" specifies the root of the raw json string and then you just specify the path to the field you want. This will always return a string. You'll have to do any casting yourself.

Be aware that it'll throw a PathNotFoundException at runtime if the path you specify doesn't exist.

Check if null Boolean is true results in exception

Boolean is the object wrapper class for the primitive boolean. This class, as any class, can indeed be null. For performance and memory reasons it is always best to use the primitive.

The wrapper classes in the Java API serve two primary purposes:

  1. To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
  2. To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.

http://en.wikipedia.org/wiki/Primitive_wrapper_class

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

Angular 2: Get Values of Multiple Checked Checkboxes

Here's a simple way using ngModel (final Angular 2)

<!-- my.component.html -->

<div class="form-group">
    <label for="options">Options:</label>
    <div *ngFor="let option of options">
        <label>
            <input type="checkbox"
                   name="options"
                   value="{{option.value}}"
                   [(ngModel)]="option.checked"/>
            {{option.name}}
        </label>
    </div>
</div>

// my.component.ts

@Component({ moduleId:module.id, templateUrl:'my.component.html'})

export class MyComponent {
  options = [
    {name:'OptionA', value:'1', checked:true},
    {name:'OptionB', value:'2', checked:false},
    {name:'OptionC', value:'3', checked:true}
  ]

  get selectedOptions() { // right now: ['1','3']
    return this.options
              .filter(opt => opt.checked)
              .map(opt => opt.value)
  }
}

Returning a stream from File.OpenRead()

Try changing your code to this:

private void Test()
{            
    System.IO.MemoryStream data = new System.IO.MemoryStream(TestStream());

    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);                       
}

How to edit HTML input value colour?

Please try this:

<input class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2" type="text" name="name" value="" placeholder="Your Name" style="background-color:blue;"/>

You basically put all the CSS inside the style part of the input tag and it works.

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

As I answered here, you can remove spines from all your plots through style settings (style sheet or rcParams):

import matplotlib as mpl

mpl.rcParams['axes.spines.left'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.bottom'] = False

Passing an integer by reference in Python

Not exactly passing a value directly, but using it as if it was passed.

x = 7
def my_method():
    nonlocal x
    x += 1
my_method()
print(x) # 8

Caveats:

  • nonlocal was introduced in python 3
  • If the enclosing scope is the global one, use global instead of nonlocal.

Adding script tag to React/JSX

According to Alex McMillan's solution, I have the following adaptation.
My own environment: React 16.8+, next v9+

// add a custom component named Script
// hooks/Script.js

import { useEffect } from 'react'

const useScript = (url, async) => {
  useEffect(() => {
    const script = document.createElement('script')

    script.src = url
    script.async = (typeof async === 'undefined' ? true : async )

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [url])
}

export default function Script({ src, async=true}) {

  useScript(src, async)

  return null  // Return null is necessary for the moment.
}

// Use the custom compoennt, just import it and substitute the old lower case <script> tag with the custom camel case <Script> tag would suffice.
// index.js

import Script from "../hooks/Script";

<Fragment>
  {/* Google Map */}
  <div ref={el => this.el = el} className="gmap"></div>

  {/* Old html script */}
  {/*<script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>*/}

  {/* new custom Script component */}
  <Script src='http://maps.google.com/maps/api/js' async={false} />
</Fragment>

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Update 2015-06

Based on antoinepairet's comment/example:

Using uib-collapse attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview

<nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">

        <!-- note the ng-init and ng-click here: -->
        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
    </div>

    <div class="collapse navbar-collapse" uib-collapse="navCollapsed">
        <ul class="nav navbar-nav">
        ...
        </ul>
    </div>
</nav>

Ancient..

I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:

The only variation from the official bootstrap example is the addition of ng- attributes noted by comments, below:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">

    <!-- note the ng-init and ng-click here: -->
    <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- note the ng-class here -->
  <div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">

    <ul class="nav navbar-nav">
    ...

Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)

This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

<html>
 <head>
  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;

    }

    function handler() {
        alert('clicked');
    }
  </script>
 </head>
 <body>
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>
 </body>
</html>

Filtering a pyspark dataframe using isin by exclusion

df.filter((df.bar != 'a') & (df.bar != 'b'))

Copying files from one directory to another in Java

    File file = fileChooser.getSelectedFile();
    String selected = fc.getSelectedFile().getAbsolutePath();
     File srcDir = new File(selected);
     FileInputStream fii;
     FileOutputStream fio;
    try {
         fii = new FileInputStream(srcDir);
         fio = new FileOutputStream("C:\\LOvE.txt");
         byte [] b=new byte[1024];
         int i=0;
        try {
            while ((fii.read(b)) > 0)
            {

              System.out.println(b);
              fio.write(b);
            }
            fii.close();
            fio.close();

How to view an HTML file in the browser with Visual Studio Code

VS Code has a Live Server Extention that support one click launch from status bar.

Some of the features:

  • One Click Launch from Status Bar
  • Live Reload
  • Support for Chrome Debugging Attachment

enter image description here

Jquery, checking if a value exists in array or not

    if ($.inArray('yourElement', yourArray) > -1)
    {
        //yourElement in yourArray
        //code here

    }

Reference: Jquery Array

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

How to convert uint8 Array to base64 Encoded String?

Very simple solution and test for JavaScript!

ToBase64 = function (u8) {
    return btoa(String.fromCharCode.apply(null, u8));
}

FromBase64 = function (str) {
    return atob(str).split('').map(function (c) { return c.charCodeAt(0); });
}

var u8 = new Uint8Array(256);
for (var i = 0; i < 256; i++)
    u8[i] = i;

var b64 = ToBase64(u8);
console.debug(b64);
console.debug(FromBase64(b64));

How do I pass a URL with multiple parameters into a URL?

Rather than html encoding your URL parameter, you need to URL encode it:

http://www.facebook.com/sharer.php?&t=FOOBAR&u=http%3A%2F%2Fwww.foobar.com%2F%3Ffirst%3D12%26sec%3D25%26position%3D

You can do this easily in most languages - in javascript:

var encodedParam = encodeURIComponent('www.foobar.com/?first=1&second=12&third=5');
// encodedParam = 'http%3A%2F%2Fwww.foobar.com%2F%3Ffirst%3D12%26sec%3D25%26position%3D'

(there are equivalent methods in other languages too)

Understanding timedelta

Because timedelta is defined like:

class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])

All arguments are optional and default to 0.

You can easily say "Three days and four milliseconds" with optional arguments that way.

>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)

And for str casting, it returns a nice formatted value instead of __repr__ to improve readability. From docs:

str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)

>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'

Checkout documentation:

http://docs.python.org/library/datetime.html#timedelta-objects

The project cannot be built until the build path errors are resolved.

Added below to pom.xml file and it worked eventually: 

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.0</version>
    <scope>provided</scope>
</dependency>

How to fast-forward a branch to head?

To rebase the current local tracker branch moving local changes on top of the latest remote state:

$ git fetch && git rebase

More generally, to fast-forward and drop the local changes (hard reset)*:

$ git fetch && git checkout ${the_branch_name} && git reset --hard origin/${the_branch_name}

to fast-forward and keep the local changes (rebase):

$ git fetch && git checkout ${the_branch_name} && git rebase origin/${the_branch_name}

* - to undo the change caused by unintentional hard reset first do git reflog, that displays the state of the HEAD in reverse order, find the hash the HEAD was pointing to before the reset operation (usually obvious) and hard reset the branch to that hash.

Convert hexadecimal string (hex) to a binary string

public static byte[] hexToBytes(String string) {
 int length = string.length();
 byte[] data = new byte[length / 2];
 for (int i = 0; i < length; i += 2) {
  data[i / 2] = (byte)((Character.digit(string.charAt(i), 16) << 4) + Character.digit(string.charAt(i + 1), 16));
 }
 return data;
}

Make git automatically remove trailing whitespace before committing

Was thinking about this today. This is all I ended up doing for a java project:

egrep -rl ' $' --include *.java *  | xargs sed -i 's/\s\+$//g'

How do I make JavaScript beep?

Solution

You can now use base64 files to produce sounds when imported as data URI. The solution is almost the same as the previous ones, except you do not need to import an external audio file.

function beep() {
    var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");  
    snd.play();
}
beep();

Compatibility

Data URI is supported on almost every browser now. More information on http://caniuse.com/datauri

Demo

http://jsfiddle.net/7EAgz/

Conversion Tool

And here is where you can convert mp3 or wav files into Data URI format:

https://dopiaza.org/tools/datauri/index.php

Java array assignment (multiple values)

Yes:

float[] values = {0.1f, 0.2f, 0.3f};

This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:

values = new float[3];

or

values = new float[] {0.1f, 0.2f, 0.3f};

Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?

How do I add a new column to a Spark DataFrame (using PySpark)?

To add new column with some custom value or dynamic value calculation which will be populated based on the existing columns.

e.g.

|ColumnA | ColumnB |
|--------|---------|
| 10     | 15      |
| 10     | 20      |
| 10     | 30      |

and new ColumnC as ColumnA+ColumnB

|ColumnA | ColumnB | ColumnC|
|--------|---------|--------|
| 10     | 15      | 25     |
| 10     | 20      | 30     |
| 10     | 30      | 40     |

using

#to add new column
def customColumnVal(row):
rd=row.asDict()
rd["ColumnC"]=row["ColumnA"] + row["ColumnB"]

new_row=Row(**rd)
return new_row
----------------------------
#convert DF to RDD
df_rdd= input_dataframe.rdd

#apply new fucntion to rdd
output_dataframe=df_rdd.map(customColumnVal).toDF()

input_dataframe is the dataframe which will get modified and customColumnVal function is having code to add new column.

How to make inline functions in C#

C# 7 adds support for local functions

Here is the previous example using a local function

void Method()
{
    string localFunction(string source)
    {
        // add your functionality here
        return source ;
    };

   // call the inline function
   localFunction("prefix");
}

Lombok added but getters and setters not recognized in Intellij IDEA

In my case it was migrating from idea 2017 to 2018 and Lombok plugin was already there. All I did is added "Enable annotation processing options" entering preferences and check the box

JQuery select2 set default value from an option in list?

For 4.x version

$('#select2Id').val(__INDEX__).trigger('change');

to select value with INDEX

$('#select2Id').val('').trigger('change');

to select nothing (show placeholder if it is)

How to run SQL in shell script

sqlplus -s /nolog <<EOF
whenever sqlerror exit sql.sqlcode;
set echo on;
set serveroutput on;

connect <SCHEMA>/<PASS>@<HOST>:<PORT>/<SID>;

truncate table tmp;

exit;
EOF

How to make a transparent HTML button?

Make a div and use your image ( png with transparent background ) as the background of the div, then you can apply any text within that div to hover over the button. Something like this:

<div class="button" onclick="yourbuttonclickfunction();" >
Your Button Label Here
</div>

CSS:

.button {
height:20px;
width:40px;
background: url("yourimage.png");
}

How to read values from the querystring with ASP.NET Core?

You can just create an object like this:

public class SomeQuery
{
    public string SomeParameter { get; set; }
    public int? SomeParameter2 { get; set; }
}

And then in controller just make something like that:

[HttpGet]
public IActionResult FindSomething([FromQuery] SomeQuery query)
{
    // Your implementation goes here..
}

Even better, you can create API model from:

[HttpGet]
public IActionResult GetSomething([FromRoute] int someId, [FromQuery] SomeQuery query)

to:

[HttpGet]
public IActionResult GetSomething(ApiModel model)

public class ApiModel
{
    [FromRoute]
    public int SomeId { get; set; }
    [FromQuery]
    public string SomeParameter { get; set; }
    [FromQuery]
    public int? SomeParameter2 { get; set; }
}

How to animate a View with Translate Animation in Android

In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.

You can try this sample code:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" android:id="@+id/rootLayout">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MOVE" android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
    <ImageView
        android:id="@+id/img3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">

        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
    </LinearLayout>

</RelativeLayout>

Your activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            ImageView img = (ImageView) findViewById( R.id.img1 );              
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img2 );
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img3 );                
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img4 );
            moveViewToScreenCenter( img );
        }
    });
}

private void moveViewToScreenCenter( View view )
{
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

    int originalPos[] = new int[2];
    view.getLocationOnScreen( originalPos );

    int xDest = dm.widthPixels/2;
    xDest -= (view.getMeasuredWidth()/2);
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;

    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
    anim.setDuration(1000);
    anim.setFillAfter( true );
    view.startAnimation(anim);
}

The method moveViewToScreenCenter gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.

GitHub relative link in Markdown file

For example, you have a repo like the following:

project/
    text.md
    subpro/
       subtext.md
       subsubpro/
           subsubtext.md
       subsubpro2/
           subsubtext2.md

The relative link to subtext.md in text.md might look like this:

[this subtext](subpro/subtext.md)

The relative link to subsubtext.md in text.md might look like this:

[this subsubtext](subpro/subsubpro/subsubtext.md)

The relative link to subtext.md in subsubtext.md might look like this:

[this subtext](../subtext.md)

The relative link to subsubtext2.md in subsubtext.md might look like this:

[this subsubtext2](../subsubpro2/subsubtext2.md)

The relative link to text.md in subsubtext.md might look like this:

[this text](../../text.md)

Waiting until two async blocks are executed before starting another block

Not to say other answers are not great for certain circumstances, but this is one snippet I always user from Google:

- (void)runSigninThenInvokeSelector:(SEL)signInDoneSel {


    if (signInDoneSel) {
        [self performSelector:signInDoneSel];
    }

}

How to find most common elements of a list?

If you are using an earlier version of Python or you have a very good reason to roll your own word counter (I'd like to hear it!), you could try the following approach using a dict.

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> word_list = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
>>> word_counter = {}
>>> for word in word_list:
...     if word in word_counter:
...         word_counter[word] += 1
...     else:
...         word_counter[word] = 1
... 
>>> popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
>>> 
>>> top_3 = popular_words[:3]
>>> 
>>> top_3
['Jellicle', 'Cats', 'and']

Top Tip: The interactive Python interpretor is your friend whenever you want to play with an algorithm like this. Just type it in and watch it go, inspecting elements along the way.

How do I perform a JAVA callback between classes?

Use the observer pattern. It works like this:

interface MyListener{
    void somethingHappened();
}

public class MyForm implements MyListener{
    MyClass myClass;
    public MyForm(){
        this.myClass = new MyClass();
        myClass.addListener(this);
    }
    public void somethingHappened(){
       System.out.println("Called me!");
    }
}
public class MyClass{
    private List<MyListener> listeners = new ArrayList<MyListener>();

    public void addListener(MyListener listener) {
        listeners.add(listener);
    }
    void notifySomethingHappened(){
        for(MyListener listener : listeners){
            listener.somethingHappened();
        }
    }
}

You create an interface which has one or more methods to be called when some event happens. Then, any class which needs to be notified when events occur implements this interface.

This allows more flexibility, as the producer is only aware of the listener interface, not a particular implementation of the listener interface.

In my example:

MyClass is the producer here as its notifying a list of listeners.

MyListener is the interface.

MyForm is interested in when somethingHappened, so it is implementing MyListener and registering itself with MyClass. Now MyClass can inform MyForm about events without directly referencing MyForm. This is the strength of the observer pattern, it reduces dependency and increases reusability.

Need to remove href values when printing in Chrome

Bootstrap does the same thing (... as the selected answer below).

@media print {
  a[href]:after {
    content: " (" attr(href) ")";
  }
}

Just remove it from there, or override it in your own print stylesheet:

@media print {
  a[href]:after {
    content: none !important;
  }
}

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

Answered provided by Tom Saleeba is very helpful. Today I also struggled with the same error

Apr 28, 2015 7:53:27 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I followed the suggestion and added the logging.properties file. And below was my reason of failure:

java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded

The root cause of the issue was a listener (Log4jConfigListener) that I added into the web.xml. And as per the link SEVERE: Exception org.springframework.web.util.Log4jConfigListener , this listener cannot be added within a WAR that is not expanded.

It may be helpful for someone to know that this was happening on OpenShift JBoss gear.

Length of a JavaScript object

The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:

_x000D_
_x000D_
Object.size = function(obj) {
  var size = 0,
    key;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) size++;
  }
  return size;
};

// Get the size of an object
const myObj = {}
var size = Object.size(myObj);
_x000D_
_x000D_
_x000D_

There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.


Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes:

var size = Object.keys(myObj).length;

This doesn't have to modify any existing prototype since Object.keys() is now built-in.

Edit: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.

Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites.

Object.keys or Object.getOwnPropertyNames does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols.

_x000D_
_x000D_
var person = {
  [Symbol('name')]: 'John Doe',
  [Symbol('age')]: 33,
  "occupation": "Programmer"
};

const propOwn = Object.getOwnPropertyNames(person);
console.log(propOwn.length); // 1

let propSymb = Object.getOwnPropertySymbols(person);
console.log(propSymb.length); // 2
_x000D_
_x000D_
_x000D_

How to get an absolute file path in Python

This always gets the right filename of the current script, even when it is called from within another script. It is especially useful when using subprocess.

import sys,os

filename = sys.argv[0]

from there, you can get the script's full path with:

>>> os.path.abspath(filename)
'/foo/bar/script.py'

It also makes easier to navigate folders by just appending /.. as many times as you want to go 'up' in the directories' hierarchy.

To get the cwd:

>>> os.path.abspath(filename+"/..")
'/foo/bar'

For the parent path:

>>> os.path.abspath(filename+"/../..")
'/foo'

By combining "/.." with other filenames, you can access any file in the system.

How to export the Html Tables data into PDF using Jspdf

There is a tablePlugin for jspdf it expects array of objects and displays that data as a table. You can style the text and headers with little changes in the code. It is open source and also has examples for you to get started with.

Java decimal formatting using String.format?

You want java.text.DecimalFormat

Send HTTP GET request with header

You do it exactly as you showed with this line:

get.setHeader("Content-Type", "application/x-zip");

So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

In my case, Run as Administrator does not help. I solved the problem by changing the Build-in Account to Local System in Configuration Manager.

Javascript - Track mouse position

Here’s a combination of the two requirements: track the mouse position, every 100 milliseconds:

var period = 100,
    tracking;

window.addEventListener("mousemove", function(e) {
    if (!tracking) {
        return;
    }

    console.log("mouse location:", e.clientX, e.clientY)
    schedule();
});

schedule();

function schedule() {
    tracking = false;

    setTimeout(function() {
        tracking = true;
    }, period);
}

This tracks & acts on the mouse position, but only every period milliseconds.

How do I import a specific version of a package using go get?

The approach I've found workable is git's submodule system. Using that you can submodule in a given version of the code and upgrading/downgrading is explicit and recorded - never haphazard.

The folder structure I've taken with this is:

+ myproject
++ src
+++ myproject
+++ github.com
++++ submoduled_project of some kind.

how to use "tab space" while writing in text file

You can use \t to create a tab in a file.

Bootstrap-select - how to fire event on change

This is what I did.

$('.selectpicker').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {
    var selected = $(e.currentTarget).val();
});

How to end C++ code

To break a condition use the return(0);

So, in your case it would be:

    if(x==1)
    {
        return 0;
    }

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.

How to set ssh timeout?

Use the -o ConnectTimeout and -o BatchMode=yes -o StrictHostKeyChecking=no .

ConnectTimeout keeps the script from hanging, BatchMode keeps it from hanging with Host unknown, YES to add to known_hosts, and StrictHostKeyChecking adds the fingerprint automatically.

**** NOTE **** The "StrictHostKeyChecking" was only intended for internal networks where you trust you hosts. Depending on the version of the SSH client, the "Are you sure you want to add your fingerprint" can cause the client to hang indefinitely (mainly old versions running on AIX). Most modern versions do not suffer from this issue. If you have to deal with fingerprints with multiple hosts, I recommend maintaining the known_hosts file with some sort of configuration management tool like puppet/ansible/chef/salt/etc.

C++ program converts fahrenheit to celsius

In your code sample you are trying to divide an integer with another integer. This is the cause of all your trouble. Here is an article that might find interesting on that subject.

With the notion of integer division you can see right away that this is not what you want in your formula. Instead, you need to use some floating point literals.

I am a rather confused by the title of this thread and your code sample. Do you want to convert Celsius degrees to Fahrenheit or do the opposite?

I will base my code sample on your own code sample until you give more details on what you want.

Here is an example of what you can do :

#include <iostream>
//no need to use the whole std namespace... use what you need :)                        
using std::cout;
using std::cin;
using std::endl;                      

int main() 
{   
    //Variables                           
    float celsius,    //represents the temperature in Celsius degrees
          fahrenheit; //represents the converted temperature in Fahrenheit degrees

    //Ask for the temperature in Celsius degrees
    cout << "Enter Celsius temperature: "; 
    cin >> celsius;

    //Formula to convert degrees in Celsius to Fahrenheit degrees
    //Important note: floating point literals need to have the '.0'!
    fahrenheit = celsius * 9.0/5.0 + 32.0;

    //Print the converted temperature to the console
    cout << "Fahrenheit = " << fahrenheit << endl;                            
}

Are there any standard exit status codes in Linux?

8 bits of the return code and 8 bits of the number of the killing signal are mixed into a single value on the return from wait(2) & co..

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>

int main() {
    int status;

    pid_t child = fork();
    if (child <= 0)
        exit(42);
    waitpid(child, &status, 0);
    if (WIFEXITED(status))
        printf("first child exited with %u\n", WEXITSTATUS(status));
    /* prints: "first child exited with 42" */

    child = fork();
    if (child <= 0)
        kill(getpid(), SIGSEGV);
    waitpid(child, &status, 0);
    if (WIFSIGNALED(status))
        printf("second child died with %u\n", WTERMSIG(status));
    /* prints: "second child died with 11" */
}

How are you determining the exit status? Traditionally, the shell only stores an 8-bit return code, but sets the high bit if the process was abnormally terminated.

$ sh -c 'exit 42'; echo $?
42
$ sh -c 'kill -SEGV $$'; echo $?
Segmentation fault
139
$ expr 139 - 128
11

If you're seeing anything other than this, then the program probably has a SIGSEGV signal handler which then calls exit normally, so it isn't actually getting killed by the signal. (Programs can chose to handle any signals aside from SIGKILL and SIGSTOP.)

SQL Server datetime LIKE select?

I am a little late to this thread but in fact there is direct support for the like operator in MS SQL server.

As documented in LIKE help if the datatype is not a string it is attempted to convert it to a string. And as documented in cast\convert documentation:

default datetime conversion to string is type 0 (,100) which is mon dd yyyy hh:miAM (or PM).

If you have a date like this in the DB:

2015-06-01 11:52:59.057

and you do queries like this:

select * from wws_invoice where invdate like 'Jun%'
select * from wws_invoice where invdate like 'Jun 1%'
select * from wws_invoice where invdate like 'Jun 1 %'
select * from wws_invoice where invdate like 'Jun 1 2015:%'
select * from wws_invoice where invdate like 'Jun ? 2015%'
...
select * from wws_invoice where invdate like 'Jun 1 2015 11:52AM'

you get that row.

However, this date format suggests that it is a DateTime2, then documentation says:

21 or 121 -- ODBC canonical (with milliseconds) default for time, date, datetime2, and datetimeoffset. -- yyyy-mm-dd hh:mi:ss.mmm(24h)

That makes it easier and you can use:

select * from wws_invoice where invdate like '2015-06-01%'

and get the invoice record. Here is a demo code:

DECLARE @myDates TABLE (myDate DATETIME2);
INSERT INTO @myDates (myDate)
VALUES
('2015-06-01 11:52:59.057'),
('2015-06-01 11:52:59.054'),
('2015-06-01 13:52:59.057'),
('2015-06-01 14:52:59.057');

SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01%';
SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01 11%';
SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01 11:52:59%';
SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01 11:52:59.054%';

Doing datetime searches in SQL server without any conversion to string has always been problematic. Getting each date part is an overkill (which unlikely would use an index). Probably a better way when you don't use string conversion would be to use range checks. ie:

select * from record 
where register_date >= '20091010' and register_date < '20091011';

sys.argv[1], IndexError: list index out of range

I've done some research and it seems that the sys.argv might require an argument at the command line when running the script

Not might, but definitely requires. That's the whole point of sys.argv, it contains the command line arguments. Like any python array, accesing non-existent element raises IndexError.

Although the code uses try/except to trap some errors, the offending statement occurs in the first line.

So the script needs a directory name, and you can test if there is one by looking at len(sys.argv) and comparing to 1+number_of_requirements. The argv always contains the script name plus any user supplied parameters, usually space delimited but the user can override the space-split through quoting. If the user does not supply the argument, your choices are supplying a default, prompting the user, or printing an exit error message.

To print an error and exit when the argument is missing, add this line before the first use of sys.argv:

if len(sys.argv)<2:
    print "Fatal: You forgot to include the directory name on the command line."
    print "Usage:  python %s <directoryname>" % sys.argv[0]
    sys.exit(1)

sys.argv[0] always contains the script name, and user inputs are placed in subsequent slots 1, 2, ...

see also:

What is the best algorithm for overriding GetHashCode?

Here is my simplistic approach. I am using the classic builder pattern for this. It is typesafe (no boxing/unboxing) and also compatbile with .NET 2.0 (no extension methods etc.).

It is used like this:

public override int GetHashCode()
{
    HashBuilder b = new HashBuilder();
    b.AddItems(this.member1, this.member2, this.member3);
    return b.Result;
} 

And here is the acutal builder class:

internal class HashBuilder
{
    private const int Prime1 = 17;
    private const int Prime2 = 23;
    private int result = Prime1;

    public HashBuilder()
    {
    }

    public HashBuilder(int startHash)
    {
        this.result = startHash;
    }

    public int Result
    {
        get
        {
            return this.result;
        }
    }

    public void AddItem<T>(T item)
    {
        unchecked
        {
            this.result = this.result * Prime2 + item.GetHashCode();
        }
    }

    public void AddItems<T1, T2>(T1 item1, T2 item2)
    {
        this.AddItem(item1);
        this.AddItem(item2);
    }

    public void AddItems<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
    }

    public void AddItems<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, 
        T4 item4)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
        this.AddItem(item4);
    }

    public void AddItems<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, 
        T4 item4, T5 item5)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
        this.AddItem(item4);
        this.AddItem(item5);
    }        

    public void AddItems<T>(params T[] items)
    {
        foreach (T item in items)
        {
            this.AddItem(item);
        }
    }
}

In C#, how to check if a TCP port is available?

When you set up a TCP connection, the 4-tuple (source-ip, source-port, dest-ip, dest-port) has to be unique - this is to ensure packets are delivered to the right place.

There is a further restriction on the server side that only one server program can bind to an incoming port number (assuming one IP address; multi-NIC servers have other powers but we don't need to discuss them here).

So, at the server end, you:

  • create a socket.
  • bind that socket to a port.
  • listen on that port.
  • accept connections on that port. and there can be multiple connections coming in (one per client).

On the client end, it's usually a little simpler:

  • create a socket.
  • open the connection. When a client opens the connection, it specifies the ip address and port of the server. It can specify its source port but usually uses zero which results in the system assigning it a free port automatically.

There is no requirement that the destination IP/port be unique since that would result in only one person at a time being able to use Google, and that would pretty well destroy their business model.

This means you can even do such wondrous things as multi-session FTP since you set up multiple sessions where the only difference is your source port, allowing you to download chunks in parallel. Torrents are a little different in that the destination of each session is usually different.

And, after all that waffling (sorry), the answer to your specific question is that you don't need to specify a free port. If you're connecting to a server with a call that doesn't specify your source port, it'll almost certainly be using zero under the covers and the system will give you an unused one.

How do I turn off PHP Notices?

I believe commenting out display_errors in php.ini won't work because the default is On. You must set it to 'Off' instead.

Don't forget to restart Apache to apply configuration changes.

Also note that while you can set display_errors at runtime, changing it here does not affect FATAL errors.

As noted by others, ideally during development you should run with error_reporting at the highest level possible and display_errors enabled. While annoying when you first start out, these errors, warnings, notices and strict coding advice all add up and enable you to becoem a better coder.

ADB Driver and Windows 8.1

There is lots of stuff on this topic, each slightly different. Like many users I spent hours trying them and got nowhere. In the end, this is what worked for me - I.e. installed the driver on windows 8.1

In my extras/google/usb_driver is a file android_winusb.inf

I double clicked on this and it "ran" and installed the driver.

I can't explain why this worked.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

Only pass name of the image, no need of 0:

img=cv2.imread('sample.jpg')

Why does Eclipse complain about @Override on interface methods?

Even after changing the compiler compliance setting to 1.6 or 1.7 from windows tab, then prefernces, then java, then compiler and setting the compiler compliance, I was still having this issue. The idea is that we need to go the the project folder, right click, Java and set compiler compliance to 1.6 or higer. This worked for me.

How to make pylab.savefig() save image for 'maximized' window instead of default size

I did the same search time ago, it seems that he exact solution depends on the backend.

I have read a bunch of sources and probably the most useful was the answer by Pythonio here How to maximize a plt.show() window using Python I adjusted the code and ended up with the function below. It works decently for me on windows, I mostly use Qt, where I use it quite often, while it is minimally tested with other backends.

Basically it consists in identifying the backend and calling the appropriate function. Note that I added a pause afterwards because I was having issues with some windows getting maximized and others not, it seems this solved for me.

def maximize(backend=None,fullscreen=False):
    """Maximize window independently on backend.
    Fullscreen sets fullscreen mode, that is same as maximized, but it doesn't have title bar (press key F to toggle full screen mode)."""
    if backend is None:
        backend=matplotlib.get_backend()
    mng = plt.get_current_fig_manager()

    if fullscreen:
        mng.full_screen_toggle()
    else:
        if backend == 'wxAgg':
            mng.frame.Maximize(True)
        elif backend == 'Qt4Agg' or backend == 'Qt5Agg':
            mng.window.showMaximized()
        elif backend == 'TkAgg':
            mng.window.state('zoomed') #works fine on Windows!
        else:
            print ("Unrecognized backend: ",backend) #not tested on different backends (only Qt)
    plt.show()

    plt.pause(0.1) #this is needed to make sure following processing gets applied (e.g. tight_layout)

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: $!";
}

Embed Google Map code in HTML with marker

The element that you posted looks like it's just copy-pasted from the Google Maps embed feature.

If you'd like to drop markers for the locations that you have, you'll need to write some JavaScript to do so. I'm learning how to do this as well.

Check out the following: https://developers.google.com/maps/documentation/javascript/overlays

It has several examples and code samples that can be easily re-used and adapted to fit your current problem.