Programs & Examples On #Colorbox

A light-weight, customizable lightbox plugin for jQuery 1.3.2+.

jQuery "on create" event for dynamically-created elements

Just came up with this solution that seems to solve all my ajax problems.

For on ready events I now use this:

function loaded(selector, callback){
    //trigger after page load.
    $(function () {
        callback($(selector));
    });
    //trigger after page update eg ajax event or jquery insert.
    $(document).on('DOMNodeInserted', selector, function () {
        callback($(this));
    });
}

loaded('.foo', function(el){
    //some action
    el.css('background', 'black');
});

And for normal trigger events I now use this:

$(document).on('click', '.foo', function () {
    //some action
    $(this).css('background', 'pink');
});

LaTeX source code listing like in professional books

For R code I use

\usepackage{listings}
\lstset{
language=R,
basicstyle=\scriptsize\ttfamily,
commentstyle=\ttfamily\color{gray},
numbers=left,
numberstyle=\ttfamily\color{gray}\footnotesize,
stepnumber=1,
numbersep=5pt,
backgroundcolor=\color{white},
showspaces=false,
showstringspaces=false,
showtabs=false,
frame=single,
tabsize=2,
captionpos=b,
breaklines=true,
breakatwhitespace=false,
title=\lstname,
escapeinside={},
keywordstyle={},
morekeywords={}
}

And it looks exactly like this

enter image description here

File changed listener in Java

I use the VFS API from Apache Commons, here is an example of how to monitor a file without much impact in performance:

DefaultFileMonitor

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

Make Bootstrap's Carousel both center AND responsive?

None of the above solutions worked for me. It's possible that there were some other styles conflicting.

For myself, the following worked, hopefully it may help someone else. I'm using bootstrap 4.

.carousel-inner img {       
   display:block;
   height: auto; 
   max-width: 100%;
}

How to enable Auto Logon User Authentication for Google Chrome

While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.

Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:

  • Launching Chrome with the auth-server-whitelist command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz". Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.
  • Installing, enabling, and configuring the AuthServerWhitelist/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.

Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:

  1. Download and unzip the latest Chrome policy templates
  2. Start > Run > gpedit.msc
  3. Navigate to Local Computer Policy > Computer Configuration > Administrative Templates
  4. Right-click Administrative Templates, and select Add/Remove Templates
  5. Add the windows\adm\en-US\chrome.adm template via the dialog
  6. In Computer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication enable and configure Authentication server whitelist
  7. Restart Chrome and navigate to chrome://policy to view active policies

Python: how to print range a-z?

Another way to do it

  import string
  pass

  aalist = list(string.ascii_lowercase)
  aaurls = ['alpha.com','bravo.com','chrly.com','delta.com',]
  iilen  =  aaurls.__len__()
  pass

  ans01 = "".join( (aalist[0:14]) )
  ans02 = "".join( (aalist[0:14:2]) )
  ans03 = "".join( "{vurl}/{vl}\n".format(vl=vjj[1],vurl=aaurls[vjj[0] % iilen]) for vjj in enumerate(aalist[0:14]) )
  pass

  print(ans01)
  print(ans02)
  print(ans03)
  pass

Result

abcdefghijklmn
acegikm
alpha.com/a
bravo.com/b
chrly.com/c
delta.com/d
alpha.com/e
bravo.com/f
chrly.com/g
delta.com/h
alpha.com/i
bravo.com/j
chrly.com/k
delta.com/l
alpha.com/m
bravo.com/n

How this differs from the other replies

  • iterate over an arbitrary number of base urls
  • cycle through the urls and do not stop until we run out of letters
  • use enumerate in conjunction with list comprehension and str.format

How do I add a border to an image in HTML?

Jack,

You can learn a great deal about borders, and how to use them at http://www.w3schools.com/css/css_border.asp. That being said, there are a couple different ways you could accomplish this.

Below is how I generally do it, but reading the documentation on w3schools you may come upon your own desired method.

.addBorder {
  /* Thickness, Style, and Color */
  border: 1px solid #000000;
}

<img src="mypicture.jpg" alt="My Picture" class="addBorder" />

Edit:

I noticed the original question was not "How to add a border to an image," but instead it was "how to add in a box around an image using html?" The question was re-written by others, so I'm not 100% sure you wanted a border on your image.

If you just wanted a box around your images, you could use a DIV, with it's own styles:

.imageBox {
  background-color:#f1f1f1;
  padding:10px;
  border:1px solid #000000;
}

<div class="imageBox">
  <img src="picture.jpg" alt="My Picture" />
</div>

Setting paper size in FPDF

They say it right there in the documentation for the FPDF constructor:

FPDF([string orientation [, string unit [, mixed size]]])

This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...

size

The size used for pages. It can be either one of the following values (case insensitive):

A3 A4 A5 Letter Legal

or an array containing the width and the height (expressed in the unit given by unit).

They even give an example with custom size:

Example with a custom 100x150 mm page size:

$pdf = new FPDF('P','mm',array(100,150));

iPhone App Icons - Exact Radius?

As others have said, you don't want to round your corners. You want to ship flat (no layers or alpha) square graphics. Apple changed the mask they use for rounding your corners in iOS7 and then again in iOS8. You can find these masks inside your Xcode application bundle. The path changes with every new SDK version they release. So, I'll show you how you can always find it.

find /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs -name 'MobileIcons.framework'

At this very moment, the path found by that command is /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/MobileIcons.framework but don't trust that. Use the command to find it yourself.

That path points to a directory with these files (again, at the time of this post)

./AppFolderBadgeIconMask-128_1only_.png
./AppFolderBadgeIconMask-16_1only_.png
./AppFolderBadgeIconMask-256_1only_.png
./AppFolderBadgeIconMask-32_1only_.png
./AppFolderBadgeIconMask-512_1only_.png
./AppFolderBadgeIconOverlay-128_1only_.png
./AppFolderBadgeIconOverlay-16_1only_.png
./AppFolderBadgeIconOverlay-256_1only_.png
./AppFolderBadgeIconOverlay-32_1only_.png
./AppFolderBadgeIconOverlay-512_1only_.png
./AppFolderBadgeIconShadow-128_1only_.png
./AppFolderBadgeIconShadow-16_1only_.png
./AppFolderBadgeIconShadow-256_1only_.png
./AppFolderBadgeIconShadow-32_1only_.png
./AppFolderBadgeIconShadow-512_1only_.png
./AppIconMask@2x~ipad.png
./AppIconMask@2x~iphone.png
./AppIconMask@3x~iphone.png
./AppIconMask~ipad.png
./AppIconMask~iphone.png
./CarAppIconMask.png
./CarNotificationAppIconMask.png
./DefaultIcon-20.png
./[email protected]
./[email protected]
./DefaultIcon-29.png
./[email protected]
./[email protected]
./DefaultIcon-40.png
./[email protected]
./[email protected]
./DefaultIcon-60@2x~iphone.png
./DefaultIcon-60@3x~iphone.png
./DefaultIcon-76@2x~ipad.png
./DefaultIcon-76~ipad.png
./DocumentBadgeMask-145.png
./[email protected]
./DocumentBadgeMask-20.png
./[email protected]
./[email protected]
./DocumentBase-320@2x~ipad.png
./DocumentBase-320~ipad.png
./DocumentBase-48.png
./[email protected]
./[email protected]
./DocumentMask-320@2x~ipad.png
./DocumentMask-320~ipad.png
./DocumentMask-48.png
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./[email protected]
./NewsstandDefaultMagazine_1only_.png
./NewsstandDefaultNewspaper_1only_.png
./NewsstandMagazineGradientLeft@2x~ipad.png
./NewsstandMagazineGradientLeft@2x~iphone.png
./NewsstandMagazineGradientLeft~ipad.png
./NewsstandMagazineGradientLeft~iphone.png
./NewsstandMagazineGradientRight@2x~ipad.png
./NewsstandMagazineGradientRight@2x~iphone.png
./NewsstandMagazineGradientRight~ipad.png
./NewsstandMagazineGradientRight~iphone.png
./NewsstandMagazineSwitcherGradientLeft.png
./[email protected]
./NewsstandNewspaperGradientBottom@2x~ipad.png
./NewsstandNewspaperGradientBottom@2x~iphone.png
./NewsstandNewspaperGradientBottom~ipad.png
./NewsstandNewspaperGradientBottom~iphone.png
./NewsstandNewspaperGradientLeft@2x~ipad.png
./NewsstandNewspaperGradientLeft@2x~iphone.png
./NewsstandNewspaperGradientLeft~ipad.png
./NewsstandNewspaperGradientLeft~iphone.png
./NewsstandNewspaperGradientRight@2x~ipad.png
./NewsstandNewspaperGradientRight@2x~iphone.png
./NewsstandNewspaperGradientRight~ipad.png
./NewsstandNewspaperGradientRight~iphone.png
./NewsstandNewspaperSwitcherGradientBottom.png
./[email protected]
./NewsstandNewspaperSwitcherGradientLeft.png
./[email protected]
./NewsstandNewspaperSwitcherGradientRight.png
./[email protected]
./NewsstandThumbnailShadow@2x~ipad.png
./NewsstandThumbnailShadow@2x~iphone.png
./NewsstandThumbnailShadow~ipad.png
./NewsstandThumbnailShadow~iphone.png
./NotificationAppIconMask.png
./[email protected]
./[email protected]
./SpotlightAppIconMask.png
./[email protected]
./[email protected]
./TableIconMask.png
./[email protected]
./[email protected]
./TableIconOutline.png
./[email protected]
./[email protected]

As you can see, there are a lot of different masks, but they are named pretty clearly. Here is the AppIconMask@3x~iphone.png image:

AppIconMask@3x~iphone.png

You can use that to test your icon to see if it will look okay after it is masked. But, don't round your corners. If you do, when Apple changes those masks again, you will have artifacts.

C# Checking if button was clicked

i am very new to this website. I am an undergraduate student, doing my Bachelor Of Computer Application. I am doing a simple program in Visual Studio using C# and I came across the same problem, how to check whether a button is clicked? I wanted to do this,

if(-button1 is clicked-) then
{
this should happen;
}
if(-button2 is clicked-) then
{
this should happen;
}

I didn't know what to do, so I tried searching for the solution in the internet. I got many solutions which didn't help me. So, I tried something on my own and did this,

int i;
private void button1_Click(object sender, EventArgs e)
        {
            i = 1;
            label3.Text = "Principle";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Simple Interest";
        }


private void button2_Click(object sender, EventArgs e)
        {
            i = 2;
            label3.Text = "SI";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Principle";
        }
private void button5_Click(object sender, EventArgs e)
        {

            try
            {
                if (i == 1)
                {
                    si = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text)) / 100;
                    textBox4.Text = Convert.ToString(si);
                }
                if (i == 2)
                {
                    p = (Convert.ToInt32(textBox1.Text) * 100) / (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text));
                    textBox4.Text = Convert.ToString(p);
                }

I declared a variable "i" and assigned it with different values in different buttons and checked the value of i in the if function. It worked. Give your suggestions if any. Thank you.

Reset Excel to default borders

My best answer for this is to simply use format painter. This might be a bit of a pain, but it works rather well as the problem you are facing is that Gridlines are covered by fill and other effects that are layered on top. Imagine putting a piece of white paper on top of your grid, the grid lines are present underneath, but they just don't show.

So try:

  1. Clicking on a cell in the spreadsheet with the format that you want
  2. Under the ribons, go to Home and format painter, it should be a smaller icon near the paste button.
  3. Now highlight any cell that you want to apply this format to and it will set the font, color, background etc. to the same as the cell selected. The value will be preserved.

From my experience this is the easiest way to do this quickly. Especially when pasting things in and out of excel.

Again this is not the programmatic way of solving this problem.

How to insert a file in MySQL database?

The BLOB datatype is best for storing files.

How to open link in new tab on html?

You could do it like this:

<a href="http://www.WEBSITE_NAME.com" target="_blank" rel="noopener noreferrer">Open</a>

Originally was:

<a href="http://www.WEBSITE_NAME.com"></a>

Also look at the following url on MDN for more information about security and privacy:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Security_and_privacy

which in turn has a link to a good article named Target="_blank" - the most underestimated vulnerability ever:

https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/

Dart: mapping a list (list.map)

I'm new to flutter. I found that one can also achieve it this way.

 tabs: [
    for (var title in movieTitles) Tab(text: title)
  ]

Note: It requires dart sdk version to be >= 2.3.0, see here

Find Oracle JDBC driver in Maven repository

You can find a Github simple sample project for use a Oracle JDBC Driver on Maven Project here.

You can find all explication for your continous integration + a sample and run on Travis-CI.

DEMO

How to check if an email address exists without sending an email?

Assuming it's the user's address, some mail servers do allow the SMTP VRFY command to actually verify the email address against its mailboxes. Most of the major site won't give you much information; the gmail response is "if you try to mail it, we'll try to deliver it" or something clever like that.

How can I output a UTF-8 CSV in PHP that Excel will read properly?

This works fine in excel for both Windows and also Mac OS.

Fix issues in excel that are not displaying characters containing diacritics, cyrillic letters, greek letter and currency symbols.

function writeCSV($filename, $headings, $data) {   

    //Use tab as field separator
    $newTab  = "\t";
    $newLine  = "\n";

    $fputcsv  =  count($headings) ? '"'. implode('"'.$newTab.'"', $headings).'"'.$newLine : '';

    // Loop over the * to export
    if (! empty($data)) {
      foreach($data as $item) {
        $fputcsv .= '"'. implode('"'.$newTab.'"', $item).'"'.$newLine;
      }
    }

    //Convert CSV to UTF-16
    $encoded_csv = mb_convert_encoding($fputcsv, 'UTF-16LE', 'UTF-8');

    // Output CSV-specific headers
    header('Set-Cookie: fileDownload=true; path=/'); //This cookie is needed in order to trigger the success window.
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$filename.csv\";" );
    header("Content-Transfer-Encoding: binary");
    header('Content-Length: '. strlen($encoded_csv));
    echo chr(255) . chr(254) . $encoded_csv; //php array convert to csv/excel

    exit;
}

commons httpclient - Adding query string parameters to GET/POST request

This is how I implemented my URL builder. I have created one Service class to provide the params for the URL

public interface ParamsProvider {

    String queryProvider(List<BasicNameValuePair> params);

    String bodyProvider(List<BasicNameValuePair> params);
}

The Implementation of methods are below

@Component
public class ParamsProviderImp implements ParamsProvider {
    @Override
    public String queryProvider(List<BasicNameValuePair> params) {
        StringBuilder query = new StringBuilder();
        AtomicBoolean first = new AtomicBoolean(true);
        params.forEach(basicNameValuePair -> {
            if (first.get()) {
                query.append("?");
                query.append(basicNameValuePair.toString());
                first.set(false);
            } else {
                query.append("&");
                query.append(basicNameValuePair.toString());
            }
        });
        return query.toString();
    }

    @Override
    public String bodyProvider(List<BasicNameValuePair> params) {
        StringBuilder body = new StringBuilder();
        AtomicBoolean first = new AtomicBoolean(true);
        params.forEach(basicNameValuePair -> {
            if (first.get()) {
                body.append(basicNameValuePair.toString());
                first.set(false);
            } else {
                body.append("&");
                body.append(basicNameValuePair.toString());
            }
        });
        return body.toString();
    }
}

When we need the query params for our URL, I simply call the service and build it. Example for that is below.

Class Mock{
@Autowired
ParamsProvider paramsProvider;
 String url ="http://www.google.lk";
// For the query params price,type
 List<BasicNameValuePair> queryParameters = new ArrayList<>();
 queryParameters.add(new BasicNameValuePair("price", 100));
 queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider

}

How can I check if a Perl array contains a particular value?

Even though it's convenient to use, it seems like the convert-to-hash solution costs quite a lot of performance, which was an issue for me.

#!/usr/bin/perl
use Benchmark;
my @list;
for (1..10_000) {
    push @list, $_;
}

timethese(10000, {
  'grep'    => sub {
            if ( grep(/^5000$/o, @list) ) {
                # code
            }
        },
  'hash'    => sub {
            my %params = map { $_ => 1 } @list;
            if ( exists($params{5000}) ) {
                # code
            }
        },
});

Output of benchmark test:

Benchmark: timing 10000 iterations of grep, hash...
          grep:  8 wallclock secs ( 7.95 usr +  0.00 sys =  7.95 CPU) @ 1257.86/s (n=10000)
          hash: 50 wallclock secs (49.68 usr +  0.01 sys = 49.69 CPU) @ 201.25/s (n=10000)

Android - Get value from HashMap

for (Object key : meMap.keySet()) {
        String value=(String)meMap.get(key);
        Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
    }

How should the ViewModel close the form?

Another solution is to create property with INotifyPropertyChanged in View Model like DialogResult, and then in Code Behind write this:

public class SomeWindow: ChildWindow
{
    private SomeViewModel _someViewModel;

    public SomeWindow()
    {
        InitializeComponent();

        this.Loaded += SomeWindow_Loaded;
        this.Closed += SomeWindow_Closed;
    }

    void SomeWindow_Loaded(object sender, RoutedEventArgs e)
    {
        _someViewModel = this.DataContext as SomeViewModel;
        _someViewModel.PropertyChanged += _someViewModel_PropertyChanged;
    }

    void SomeWindow_Closed(object sender, System.EventArgs e)
    {
        _someViewModel.PropertyChanged -= _someViewModel_PropertyChanged;
        this.Loaded -= SomeWindow_Loaded;
        this.Closed -= SomeWindow_Closed;
    }

    void _someViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == SomeViewModel.DialogResultPropertyName)
        {
            this.DialogResult = _someViewModel.DialogResult;
        }
    }
}

The most important fragment is _someViewModel_PropertyChanged. DialogResultPropertyName can be some public const string in SomeViewModel.

I use this kind of trick to make some changes in View Controls in case when this is hard to do in ViewModel. OnPropertyChanged in ViewModel you can do anything you want in View. ViewModel is still 'unit testable' and some small lines of code in code behind makes no difference.

Enable binary mode while restoring a Database from an SQL dump

In Windows machine, please follows the preceding steps.

  1. Open file in notepad.
  2. Click on Save as
  3. Select Encoding type UTF-8.

Now source your db.

How do I configure different environments in Angular.js?

You could use lvh.me:9000 to access your AngularJS app, (lvh.me just points to 127.0.0.1) and then specify a different endpoint if lvh.me is the host:

app.service("Configuration", function() {
  if (window.location.host.match(/lvh\.me/)) {
    return this.API = 'http://localhost\\:7080/myapi/';
  } else {
    return this.API = 'http://localhost\\:8099/hisapi/';
  }
});

And then inject the Configuration service and use Configuration.API wherever you need to access the API:

$resource(Configuration.API + '/endpoint/:id', {
  id: '@id'
});

A tad clunky, but works fine for me, albeit in a slightly different situation (API endpoints differ in production and development).

Parsing ISO 8601 date in Javascript

If you want to keep it simple, this should suffice:

function parseIsoDatetime(dtstr) {
    var dt = dtstr.split(/[: T-]/).map(parseFloat);
    return new Date(dt[0], dt[1] - 1, dt[2], dt[3] || 0, dt[4] || 0, dt[5] || 0, 0);
}

note parseFloat is must, parseInt doesn't always work. Map requires IE9 or later.

Works for formats:

  • 2014-12-28 15:30:30
  • 2014-12-28T15:30:30
  • 2014-12-28

Not valid for timezones, see other answers about those.

Two Radio Buttons ASP.NET C#

     <asp:RadioButtonList id="RadioButtonList1" runat="server">
        <asp:ListItem Selected="True">Metric</asp:ListItem>
        <asp:ListItem>US</asp:ListItem>
     </asp:RadioButtonList>

Java, How to add values to Array List used as value in HashMap

You could either use the Google Guava library, which has implementations for Multi-Value-Maps (Apache Commons Collections has also implementations, but without generics).

However, if you don't want to use an external lib, then you would do something like this:

if (map.get(id) == null) { //gets the value for an id)
    map.put(id, new ArrayList<String>()); //no ArrayList assigned, create new ArrayList

map.get(id).add(value); //adds value to list.

Add Twitter Bootstrap icon to Input box

For bootstrap 4

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

            <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
        <form class="form-inline my-2 my-lg-0">
                        <div class="input-group">
                            <input class="form-control" type="search" placeholder="Search">
                            <div class="input-group-append">
                                <div class="input-group-text"><i class="fa fa-search"></i></div>
                            </div>
                        </div>
                    </form>

Demo

Get path to execution directory of Windows Forms application

Check this out:

Imports System.IO
Imports System.Management

Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)
        Process.Start(TextBox1.Text)
    End Sub
End Class

Can't install any packages in Node.js using "npm install"

This error might also occur due to proxy settings, once check that your proxy allow the access to npm commands.

It worked for me quite well.

Call removeView() on the child's parent first

What I was doing wrong so I got this error is I wasn't instantiating dynamic layout and adding childs to it so got this error

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

Mocking member variables of a class using Mockito

You need to provide a way of accessing the member variables so you can pass in a mock (the most common ways would be a setter method or a constructor which takes a parameter).

If your code doesn't provide a way of doing this, it's incorrectly factored for TDD (Test Driven Development).

How can I dynamically switch web service addresses in .NET without a recompile?

As long as the web service methods and underlying exposed classes do not change, it's fairly trivial. With Visual Studio 2005 (and newer), adding a web reference creates an app.config (or web.config, for web apps) section that has this URL. All you have to do is edit the app.config file to reflect the desired URL.

In our project, our simple approach was to just have the app.config entries commented per environment type (development, testing, production). So we just uncomment the entry for the desired environment type. No special coding needed there.

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

For loop example in MySQL

Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below

CREATE TABLE `table1` (
    `col1` VARCHAR(50) NULL DEFAULT NULL
)

Now if you want to insert number from 1 to 50 in that table then use following stored procedure

DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      DECLARE a INT Default 1 ;
      simple_loop: LOOP         
         insert into table1 values(a);
         SET a=a+1;
         IF a=51 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

To call that stored procedure use

CALL `ABC`()

How can I validate a string to only allow alphanumeric characters in it?

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the https://www.nuget.org/packages/Extensions.cs package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "smith23".IsAlphaNumeric() will return True whereas "smith 23".IsAlphaNumeric(false) will return False. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden as shown above. If you want to allow spaces such that "smith 23".IsAlphaNumeric() will return True, simple default the arg.
  4. Every other check in the rest of the code is simply MyString.IsAlphaNumeric().

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

Get top n records for each group of grouped results

Try this:

SELECT a.person, a.group, a.age FROM person AS a WHERE 
(SELECT COUNT(*) FROM person AS b 
WHERE b.group = a.group AND b.age >= a.age) <= 2 
ORDER BY a.group ASC, a.age DESC

DEMO

Read a plain text file with php

http://php.net/manual/en/function.file-get-contents.php
http://php.net/manual/en/function.explode.php

$array = explode("\n", file_get_contents($filename));

This wont actually read it line by line, but it will get you an array which can be used line by line. There are a number of alternatives.

How do I turn off PHP Notices?

I found this trick out recently. Whack an @ at the start of a line that may produce an warning/error.

As if by magic, they dissapear.

Converting NSData to NSString in Objective c

in objective C:

NSData *tmpData;
NSString *tmpString = [NSString stringWithFormat:@"%@", tmpData];
NSLog(tmpString)

How to view AndroidManifest.xml from APK file?

Android Studio can now show this. Go to Build > Analyze APK... and select your apk. Then you can see the content of the AndroidManifset file.

How to throw a C++ exception

Simple:

#include <stdexcept>

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}

The Standard Library comes with a nice collection of built-in exception objects you can throw. Keep in mind that you should always throw by value and catch by reference:

try {
    compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
    // do stuff with exception... 
}

You can have multiple catch() statements after each try, so you can handle different exception types separately if you want.

You can also re-throw exceptions:

catch( const std::invalid_argument& e ) {
    // do something

    // let someone higher up the call stack handle it if they want
    throw;
}

And to catch exceptions regardless of type:

catch( ... ) { };

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

How to get last key in an array?

Just use : echo $array[count($array) - 1];

JOIN queries vs multiple queries

There are several factors which means there is no binary answer. The question of what is best for performance depends on your environment. By the way, if your single select with an identifier is not sub-second, something may be wrong with your configuration.

The real question to ask is how do you want to access the data. Single selects support late-binding. For example if you only want employee information, you can select from the Employees table. The foreign key relationships can be used to retrieve related resources at a later time and as needed. The selects will already have a key to point to so they should be extremely fast, and you only have to retrieve what you need. Network latency must always be taken into account.

Joins will retrieve all of the data at once. If you are generating a report or populating a grid, this may be exactly what you want. Compiled and optomized joins are simply going to be faster than single selects in this scenario. Remember, Ad-hoc joins may not be as fast--you should compile them (into a stored proc). The speed answer depends on the execution plan, which details exactly what steps the DBMS takes to retrieve the data.

How to recover the deleted files using "rm -R" command in linux server?

Short answer: You can't. rm removes files blindly, with no concept of 'trash'.

Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i by default, but not all do.

Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete.

In the future, use rm with caution. Either create a del alias that provides interactivity, or use a file manager.

How to ensure a <select> form field is submitted when it is disabled?

Another option is to use the readonly attribute.

<select readonly="readonly">
    ....
</select>

With readonly the value is still submitted, the input field is grayed out and the user cannot edit it.

Edit:

Quoted from http://www.w3.org/TR/html401/interact/forms.html#adef-readonly:

  • Read-only elements receive focus but cannot be modified by the user.
  • Read-only elements are included in tabbing navigation.
  • Read-only elements may be successful.

When it says the element may be succesful, it means it may be submitted, as stated here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls

How to handle button clicks using the XML onClick within Fragments

This has been working for me:(Android studio)

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.update_credential, container, false);
        Button bt_login = (Button) rootView.findViewById(R.id.btnSend);

        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                System.out.println("Hi its me");


            }// end onClick
        });

        return rootView;

    }// end onCreateView

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

There are a couple things missing, both from the solutions above and also from the Microsoft documentation. If you follow the link to the GitHub repository linked from the documentation above, you'll find the real solution.

I think the confusion lies with the fact that the default templates that many people are using do not contain the default constructor for Startup, so people don't necessarily know where the injected Configuration is coming from.

So, in Startup.cs, add:

 public IConfiguration Configuration { get; }
 public Startup(IConfiguration configuration) 
 {
     Configuration = configuration;
 }

and then in ConfigureServices method add what other people have said...

services.AddDbContext<ChromeContext>(options =>                    
    options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection")));

you also have to ensure that you've got your appsettings.json file created and have a connection strings section similar to this

{
  "ConnectionStrings": {
    "DatabaseConnection": "Server=MyServer;Database=MyDatabase;Persist Security Info=True;User ID=SA;Password=PASSWORD;MultipleActiveResultSets=True;"
  }
}

Of course, you will have to edit that to reflect your configuration.

Things to keep in mind. This was tested using Entity Framework Core 3 in a .Net Standard 2.1 project. I needed to add the nuget packages for: Microsoft.EntityFrameworkCore 3.0.0 Microsoft.EntityFrameworkCore.SqlServer 3.0.0 because that's what I'm using, and that's what is required to get access to the UseSqlServer.

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

Check if password you are using is correct one by running below command

keytool -keypasswd -new temp123 -keystore awsdemo-keystore.jks -storepass temp123 -alias movie-service -keypass changeit

If you are getting below error then your password is wrong

keytool error: java.security.UnrecoverableKeyException: Cannot recover key

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

Should a RESTful 'PUT' operation return something

The HTTP specification (RFC 2616) has a number of recommendations that are applicable. Here is my interpretation:

  • HTTP status code 200 OK for a successful PUT of an update to an existing resource. No response body needed. (Per Section 9.6, 204 No Content is even more appropriate.)
  • HTTP status code 201 Created for a successful PUT of a new resource, with the most specific URI for the new resource returned in the Location header field and any other relevant URIs and metadata of the resource echoed in the response body. (RFC 2616 Section 10.2.2)
  • HTTP status code 409 Conflict for a PUT that is unsuccessful due to a 3rd-party modification, with a list of differences between the attempted update and the current resource in the response body. (RFC 2616 Section 10.4.10)
  • HTTP status code 400 Bad Request for an unsuccessful PUT, with natural-language text (such as English) in the response body that explains why the PUT failed. (RFC 2616 Section 10.4)

How can I do factory reset using adb in android?

Warning

From @sidharth: "caused my lava iris alfa to go into a bootloop :("


For my Motorola Nexus 6 running Android Marshmallow 6.0.1 I did:

adb devices       # Check the phone is running
adb reboot bootloader
# Wait a few seconds
fastboot devices  # Check the phone is in bootloader
fastboot -w       # Wipe user data

How do I add a newline to a windows-forms TextBox?

Quickie test code for WinForms in VB:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim Newline As String
    Newline = System.Environment.NewLine

    TextBox1.Text = "This is a test"
    TextBox1.Text = TextBox1.Text & Newline & "This is line 2"

End Sub

How can I make a .NET Windows Forms application that only runs in the System Tray?

It is very friendly framework for Notification Area Application... it is enough to add NotificationIcon to base form and change auto-generated code to code below:

public partial class Form1 : Form
{
    private bool hidden = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.ShowInTaskbar = false;
        //this.WindowState = FormWindowState.Minimized;
        this.Hide();
        hidden = true;
    }

    private void notifyIcon1_Click(object sender, EventArgs e)
    {
        if (hidden) // this.WindowState == FormWindowState.Minimized)
        {
            // this.WindowState = FormWindowState.Normal;
            this.Show();
            hidden = false;
        }
        else
        {
            // this.WindowState = FormWindowState.Minimized;
            this.Hide();
            hidden = true;
        }
    }
}

Valid characters of a hostname?

It depends on whether you process IDNs before or after the IDN toASCII algorithm (that is, do you see the domain name pa??de??µa.d???µ? in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp?).

In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:

U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).

and U+002E (.) of course; the rules for labels allow the others, with dots between labels.

If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.

Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar.

How to get POSTed JSON in Flask?

Try to use force parameter...

request.get_json(force = True)

How to force Sequential Javascript Execution?

In javascript, there is no way, to make the code wait. I've had this problem and the way I did it was do a synchronous SJAX call to the server, and the server actually executes sleep or does some activity before returning and the whole time, the js waits.

Eg of Sync AJAX: http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX

Is java.sql.Timestamp timezone specific?

I think the correct answer should be java.sql.Timestamp is NOT timezone specific. Timestamp is a composite of java.util.Date and a separate nanoseconds value. There is no timezone information in this class. Thus just as Date this class simply holds the number of milliseconds since January 1, 1970, 00:00:00 GMT + nanos.

In PreparedStatement.setTimestamp(int parameterIndex, Timestamp x, Calendar cal) Calendar is used by the driver to change the default timezone. But Timestamp still holds milliseconds in GMT.

API is unclear about how exactly JDBC driver is supposed to use Calendar. Providers seem to feel free about how to interpret it, e.g. last time I worked with MySQL 5.5 Calendar the driver simply ignored Calendar in both PreparedStatement.setTimestamp and ResultSet.getTimestamp.

How to combine two strings together in PHP?

$result = $data1 . $data2;

try this

Genymotion error at start 'Unable to load virtualbox'

Don't ask what this has to do with that , but by right clicking the genymotion application file and changing to compatibility to Vista solved the problem!

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

UIAlertController custom font, size, color

Swift 5 and 5.1. Create a separate file and put UIAlertController Customization code there

import Foundation
import  UIKit

extension UIAlertController {

  //Set background color of UIAlertController
  func setBackgroudColor(color: UIColor) {
    if let bgView = self.view.subviews.first,
      let groupView = bgView.subviews.first,
      let contentView = groupView.subviews.first {
      contentView.backgroundColor = color
    }
  }

  //Set title font and title color
  func setTitle(font: UIFont?, color: UIColor?) {
    guard let title = self.title else { return }
    let attributeString = NSMutableAttributedString(string: title)//1
    if let titleFont = font {
      attributeString.addAttributes([NSAttributedString.Key.font : titleFont],//2
        range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributeString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor],//3
        range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributeString, forKey: "attributedTitle")//4
  }

  //Set message font and message color
  func setMessage(font: UIFont?, color: UIColor?) {
    guard let title = self.message else {
      return
    }
    let attributedString = NSMutableAttributedString(string: title)
    if let titleFont = font {
      attributedString.addAttributes([NSAttributedString.Key.font : titleFont], range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributedString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor], range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributedString, forKey: "attributedMessage")//4
  }

  //Set tint color of UIAlertController
  func setTint(color: UIColor) {
    self.view.tintColor = color
  }
}

Now On any action Show Alert

  func tapShowAlert(sender: UIButton) {
    let alertController = UIAlertController(title: "Alert!!", message: "This is custom alert message", preferredStyle: .alert)
    // Change font and color of title
    alertController.setTitle(font: UIFont.boldSystemFont(ofSize: 26), color: UIColor.yellow)
    // Change font and color of message
    alertController.setMessage(font: UIFont(name: "AvenirNextCondensed-HeavyItalic", size: 18), color: UIColor.red)
    // Change background color of UIAlertController
    alertController.setBackgroudColor(color: UIColor.black)
    let actnOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
    let actnCancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(actnOk)
    alertController.addAction(actnCancel)
    self.present(alertController, animated: true, completion: nil)
  }

Result

enter image description here

javascript return true or return false when and how to use it?

returning true or false indicates that whether execution should continue or stop right there. So just an example

<input type="button" onclick="return func();" />

Now if func() is defined like this

function func()
{
 // do something
return false;
}

the click event will never get executed. On the contrary if return true is written then the click event will always be executed.

Make Vim show ALL white spaces as a character

As of patch 7.4.710 you can now set a character to show in place of space using listchars!

:set listchars+=space:?

So, to show ALL white space characters as a character you can do the following:

:set listchars=eol:¬,tab:>·,trail:~,extends:>,precedes:<,space:?
:set list

Discussion on mailing list: https://groups.google.com/forum/?fromgroups#!topic/vim_dev/pjmW6wOZW_Q

Making button go full-width?

<div class="col-md-9">
    <button class="btn btn-block btn-primary" type="button">Block level button</button>
</div>

In Bootstrap 3, this should be all you need. I believe btn-large was overriding the width of btn-block.

Is there a unique Android device ID?

How about the IMEI. That is unique for Android or other mobile devices.

How do I implement charts in Bootstrap?

Github did this using the HTML canvas element.

This specification defines the 2D Context for the HTML canvas element. The 2D Context provides objects, methods, and properties to draw and manipulate graphics on a canvas drawing surface.

If you use a browser inspector, you see inside every list element a div with a canvas element.

<div class="participation-graph">
   <canvas class="bars" data-color-all="#F5F5F5" data-color-owner="#F5F5F5" data-source="/mxcl/homebrew/graphs/owner_participation" height="80" width="640"></canvas>
</div>

With CSS (z-index, position...) you can put that canvas in the background of a li element or table, in your case.

Do a search about jquery pluggins that fit your requirement.

Hope this pointers help you to achieve that.

How to make Twitter Bootstrap tooltips have multiple lines?

If you are using Angular UI Bootstrap, you can use tooltip with html syntax: tooltip-html-unsafe

e.g. update to angular 1.2.10 & angular-ui-bootstrap 0.11: http://jsfiddle.net/aX2vR/1/

old one: http://jsfiddle.net/8LMwz/1/

Angular 2 / 4 / 5 - Set base href dynamically

Based on your (@sharpmachine) answer, I was able to further refactor it a little, so that we don't have to hack out a function in index.html.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';

import { AppComponent } from './';
import { getBaseLocation } from './shared/common-functions.util';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpModule,
  ],
  bootstrap: [AppComponent],
  providers: [
    appRoutingProviders,
    {
        provide: APP_BASE_HREF,
        useFactory: getBaseLocation
    },
  ]
})
export class AppModule { }

And, ./shared/common-functions.util.ts contains:

export function getBaseLocation() {
    let paths: string[] = location.pathname.split('/').splice(1, 1);
    let basePath: string = (paths && paths[0]) || 'my-account'; // Default: my-account
    return '/' + basePath;
}

How to return a result from a VBA function

VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:

test = 1

Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.

element with the max height from a set of elements

Use .map() and Math.max.

var maxHeight = Math.max.apply(null, $("div.panel").map(function ()
{
    return $(this).height();
}).get());

If that's confusing to read, this might be clearer:

var heights = $("div.panel").map(function ()
    {
        return $(this).height();
    }).get();

maxHeight = Math.max.apply(null, heights);

What's the -practical- difference between a Bare and non-Bare repository?

This is not a new answer, but it helped me to understand the different aspects of the answers above (and it is too much for a comment).

Using Git Bash just try:

me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../

me@pc MINGW64 /c/Test
$ git init
Initialized empty Git repository in C:/Test/.git/

me@pc MINGW64 /c/Test (master)
$ ls -al
total 20
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 .git/

me@pc MINGW64 /c/Test (master)
$ cd .git

me@pc MINGW64 /c/Test/.git (GIT_DIR!)
$ ls -al
total 15
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ../
-rw-r--r-- 1 myid 1049089 130 Apr  1 11:35 config
-rw-r--r-- 1 myid 1049089  73 Apr  1 11:35 description
-rw-r--r-- 1 myid 1049089  23 Apr  1 11:35 HEAD
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 hooks/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 info/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 objects/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 refs/

Same with git --bare:

me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:36 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../

me@pc MINGW64 /c/Test
$ git init --bare
Initialized empty Git repository in C:/Test/

me@pc MINGW64 /c/Test (BARE:master)
$ ls -al
total 23
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 ./
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:11 ../
-rw-r--r-- 1 myid 1049089 104 Apr  1 11:36 config
-rw-r--r-- 1 myid 1049089  73 Apr  1 11:36 description
-rw-r--r-- 1 myid 1049089  23 Apr  1 11:36 HEAD
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 hooks/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 info/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 objects/

Initialize array of strings

There is no right way, but you can initialize an array of literals:

char **values = (char *[]){"a", "b", "c"};

or you can allocate each and initialize it:

char **values = malloc(sizeof(char*) * s);
for(...)
{
    values[i] = malloc(sizeof(char) * l);
    //or
    values[i] = "hello";
}

How to write data to a text file without overwriting the current data

Change your constructor to pass true as the second argument.

TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

The problem for me seems to have been how the user has been setup on my local machine to. Using the command
git push -u origin master
was causing the error. Removing the switch -u to have
git push origin master
solved it for me. It can be scary to imagine how user setup can result in an error related to LibreSSL.

How to install PyQt5 on Windows?

I'm new to both Python and PyQt5. I tried to use pip, but I was having problems with it using a Windows machine. If you have a version of Python 3.4 or above, pip is installed and ready to use like so:

python -m pip install pyqt5 

That's of course assuming that the path for Python executable is in your PATH environment variable. Otherwise include the full path to Python executable (you can type where python to the Command Window to find it) like:

C:\users\userName\AppData\Local\Programs\Python\Python34\python.exe -m pip install pyqt5

How to read from standard input in the console?

Can also be done like this:-

package main
import "fmt"     

func main(){
    var myname string
fmt.Scanf("%s", &myname)           
fmt.Println("Hello", myname)       
}

How to find my php-fpm.sock?

I faced this same issue on CentOS 7 years later

Posting hoping that it may help others...

Steps:

FIRST, configure the php-fpm settings:

-> systemctl stop php-fpm.service

-> cd /etc/php-fpm.d

-> ls -hal (should see a www.conf file)

-> cp www.conf www.conf.backup (back file up just in case)

-> vi www.conf

-> :/listen = (to get to the line we need to change)

-> i (to enter VI's text insertion mode)

-> change from listen = 127.0.0.1:9000 TO listen = /var/run/php-fpm/php-fpm.sock

-> Esc then :/listen.owner (to find it) then i (to change)

-> UNCOMMENT the listen.owner = nobody AND listen.group = nobody lines

-> Hit Esc then type :/user = then i

-> change user = apache TO user = nginx

-> AND change group = apache TO group = nginx

-> Hit Esc then :wq (to save and quit)

-> systemctl start php-fpm.service (now you will have a php-fpm.sock file)

SECOND, you configure your server {} block in your /etc/nginx/nginx.conf file. Then run:systemctl restart nginx.service

FINALLY, create a new .php file in your /usr/share/nginx/html directory for your Nginx server to serve up via the internet browser as a test.

-> vi /usr/share/nginx/html/mytest.php

-> type o

-> <?php echo date("Y/m/d-l"); ?> (PHP page will print date and day in browser)

-> Hit Esc

-> type :wq (to save and quite VI editor)

-> open up a browser and go to: http://yourDomainOrIPAddress/mytest.php (you should see the date and day printed)

Build project into a JAR automatically in Eclipse

Regarding to Peter's answer and Micheal's addition to it you may find How Do I Automatically Generate A .jar File In An Eclipse Java Project useful. Because even you have "*.jardesc" file on your project you have to run it manually. It may cools down your "eclipse click hassle" a bit.

Read input from console in Ruby?

There are many ways to take input from the users. I personally like using the method gets. When you use gets, it gets the string that you typed, and that includes the ENTER key that you pressed to end your input.

name = gets
"mukesh\n"

You can see this in irb; type this and you will see the \n, which is the “newline” character that the ENTER key produces: Type name = gets you will see somethings like "mukesh\n" You can get rid of pesky newline character using chomp method.

The chomp method gives you back the string, but without the terminating newline. Beautiful chomp method life saviour.

name = gets.chomp
"mukesh"

You can also use terminal to read the input. ARGV is a constant defined in the Object class. It is an instance of the Array class and has access to all the array methods. Since it’s an array, even though it’s a constant, its elements can be modified and cleared with no trouble. By default, Ruby captures all the command line arguments passed to a Ruby program (split by spaces) when the command-line binary is invoked and stores them as strings in the ARGV array.

When written inside your Ruby program, ARGV will take take a command line command that looks like this:

test.rb hi my name is mukesh

and create an array that looks like this:

["hi", "my", "name", "is", "mukesh"]

But, if I want to passed limited input then we can use something like this.

test.rb 12 23

and use those input like this in your program:

a = ARGV[0]
b = ARGV[1]

Single controller with multiple GET methods in ASP.NET Web API

In VS 2019, this works with ease:

[Route("api/[controller]/[action]")] //above the controller class

And in the code:

[HttpGet]
[ActionName("GetSample1")]
public Ilist<Sample1> GetSample1()
{
    return getSample1();
}
[HttpGet]
[ActionName("GetSample2")]
public Ilist<Sample2> GetSample2()
{
    return getSample2();
}
[HttpGet]
[ActionName("GetSample3")]
public Ilist<Sample3> GetSample3()
{
    return getSample3();
}
[HttpGet]
[ActionName("GetSample4")]
public Ilist<Sample4> GetSample4()
{
    return getSample4();
}

You can have multiple gets like above mentioned.

The static keyword and its various uses in C++

When you a declare a static variable at file scope, then that variable is only available in that particular file (technically, the *translation unit, but let's not complicate this too much). For example:

a.cpp

static int x = 7;

void printax()
{
    cout << "from a.cpp: x=" << x << endl;
}

b.cpp

static int x = 9;

void printbx()
{
    cout << "from b.cpp: x=" << x << endl;
}

main.cpp:

int main(int, char **)
{
    printax(); // Will print 7
    printbx(); // Will print 9

    return 0;
}

For a local variable, static means that the variable will be zero-initialized and retain its value between calls:

unsigned int powersoftwo()
{
    static unsigned lastpow;

    if(lastpow == 0)
        lastpow = 1;
    else
        lastpow *= 2;

    return lastpow;
}

int main(int, char **)
{
    for(int i = 0; i != 10; i++)
        cout << "2^" << i << " = " << powersoftwo() << endl;
}

For class variables, it means that there is only a single instance of that variable that is shared among all members of that class. Depending on permissions, the variable can be accessed from outside the class using its fully qualified name.

class Test
{
private:
    static char *xxx;

public:
    static int yyy;

public:
    Test()
    {        
        cout << this << "The static class variable xxx is at address "
             << static_cast<void *>(xxx) << endl;
        cout << this << "The static class variable yyy is at address "
             << static_cast<void *>(&y) << endl;
    }
};

// Necessary for static class variables.
char *Test::xxx = "I'm Triple X!";
int Test::yyy = 0;

int main(int, char **)
{
    Test t1;
    Test t2;

    Test::yyy = 666;

    Test t3;
};

Marking a non-class function as static makes the function only accessible from that file and inaccessible from other files.

a.cpp

static void printfilename()
{ // this is the printfilename from a.cpp - 
  // it can't be accessed from any other file
    cout << "this is a.cpp" << endl;
}

b.cpp

static void printfilename()
{ // this is the printfilename from b.cpp - 
  // it can't be accessed from any other file
    cout << "this is b.cpp" << endl;
}

For class member functions, marking them as static means that the function doesn't need to be called on a particular instance of an object (i.e. it doesn't have a this pointer).

class Test
{
private:
    static int count;

public:
    static int GetTestCount()
    {
        return count;
    };

    Test()
    {
        cout << this << "Created an instance of Test" << endl;
        count++;
    }

    ~Test()
    {
        cout << this << "Destroyed an instance of Test" << endl;
        count--;
    }
};

int Test::count = 0;

int main(int, char **)
{
    Test *arr[10] = { NULL };

    for(int i = 0; i != 10; i++)
        arr[i] = new Test();

    cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;

    // now, delete them all except the first and last!
    for(int i = 1; i != 9; i++)
        delete arr[i];        

    cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;

    delete arr[0];

    cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;

    delete arr[9];

    cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;

    return 0;
}

How to tell if a string is not defined in a Bash shell script

A summary of tests.

[ -n "$var" ] && echo "var is set and not empty"
[ -z "$var" ] && echo "var is unset or empty"
[ "${var+x}" = "x" ] && echo "var is set"  # may or may not be empty
[ -n "${var+x}" ] && echo "var is set"  # may or may not be empty
[ -z "${var+x}" ] && echo "var is unset"
[ -z "${var-x}" ] && echo "var is set and empty"

How can a web application send push notifications to iOS devices?

You can use HTML5 Websockets to introduce your own push messages. From Wikipedia:

"For the client side, WebSocket was to be implemented in Firefox 4, Google Chrome 4, Opera 11, and Safari 5, as well as the mobile version of Safari in iOS 4.2. Also the BlackBerry Browser in OS7 supports WebSockets."

To do this, you need your own provider server to push the messages to the clients.
If you want to use APN (Apple Push Notification) or C2DM (Cloud to Device Message), you must have a native application which must be downloaded through the online store.

Set default host and port for ng serve in config file

enter image description here

Only one thing you have to do. Type this in in your Command Prompt: ng serve --port 4021 [or any other port you want to assign eg: 5050, 5051 etc ]. No need to do changes in files.

Call parent method from child class c#

Found the solution.

In the parent I declare a new instance of the ChildClass() then bind the event handler in that class to the local method in the parent

In the child class I add a public event handler:

public EventHandler UpdateProgress;

In the parent I create a new instance of this child class then bind the local parent event to the public eventhandler in the child

ChildClass child = new ChildClass();
child.UpdateProgress += this.MyMethod;
child.LoadData(this.MyDataTable);

Then in the LoadData() of the child class I can call

private LoadData() {
    this.OnMyMethod();
}

Where OnMyMethod is:

public void OnMyMethod()
{
     // has the event handler been assigned?
     if (this.UpdateProgress!= null)
     {
         // raise the event
         this.UpdateProgress(this, new EventArgs());
     }
}

This runs the event in the parent class

Getting the array length of a 2D array in Java

import java.util.Arrays;

public class Main {

    public static void main(String[] args) 
    {

        double[][] test = { {100}, {200}, {300}, {400}, {500}, {600}, {700}, {800}, {900}, {1000}};

        int [][] removeRow = { {0}, {1}, {3}, {4}, };

        double[][] newTest = new double[test.length - removeRow.length][test[0].length];

        for (int i = 0, j = 0, k = 0; i < test.length; i++) {
            if (j < removeRow.length) {
                if (i == removeRow[j][0]) {
                    j++;
                    continue;
                }
            }
            newTest[k][0] = test[i][0];
            k++;
        }

        System.out.println(Arrays.deepToString(newTest));   
    }
}

Android Fragment onClick button Method

If you want to use data binding you can follow this solution The following solution might be a better one to follow. the layout is in fragment_my.xml

<data>
    <variable
        name="listener"
        type="my_package.MyListener" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <Button
        android:id="@+id/moreTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="@{() -> listener.onClick()}"
        android:text="@string/login"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
And the Fragment would be as follows
class MyFragment : Fragment(), MyListener {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
            return FragmentMyBinding.inflate(
                inflater,
                container,
                false
            ).apply {
                lifecycleOwner = viewLifecycleOwner
                listener = this@MyFragment
            }.root
    }

    override fun onClick() {
        TODO("Not yet implemented")
    }

}

interface MyListener{
    fun onClick()
}

Visual Studio Code: Auto-refresh file changes

VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.

There is currently no way to disable this behaviour.

How to get the current TimeStamp?

In Qt 4.7, there is the QDateTime::currentMSecsSinceEpoch() static function, which does exactly what you need, without any intermediary steps. Hence I'd recommend that for projects using Qt 4.7 or newer.

How to convert an address into a Google Maps Link (NOT MAP)

Borrowing from Michael Jasper's and Jon Hendershot's solutions, I offer the following:

$('address').each(function() {
    var text = $(this).text();

    var q    = $.trim(text).replace(/\r?\n/, ',').replace(/\s+/g, ' ');
    var link = '<a href="http://maps.google.com/maps?q=' + encodeURIComponent(q) + '" target="_blank"></a>';

    return $(this).wrapInner(link);
});

This solution offers the following benefits over solutions previously offered:

  • It will not remove HTML tags (e.g. <br> tags) within <address>, so formatting is preserved
  • It properly encodes the URL
  • It squashes extra spaces so that the generated URL is shorter and cleaner and human-readable after encoding
  • It produces valid markup (Mr.Hendershot's solution creates <a><address></address></a> which is invalid because block-level elements such as <address> are not permitted within inline elements such as <a>.

Caveat: If your <address> tag contains block-level elements like <p> or <div>, then this JavaScript code will produce in invalid markup (because the <a> tag will contain those block-level elements). But if you're just doing stuff like this:

<address>
  The White House
  <br>
  1600 Pennsylvania Ave NW
  <br>
  Washington, D.C.  20500
</address>

Then it'll work just fine.

Terminal Commands: For loop with echo

jot would work too (in bash shell)

for i in `jot 1000 1`; do echo "http://example.com/$i.jpg"; done

Adding a y-axis label to secondary y-axis in matplotlib

I don't have access to Python right now, but off the top of my head:

fig = plt.figure()

axes1 = fig.add_subplot(111)
# set props for left y-axis here

axes2 = axes1.twinx()   # mirror them
axes2.set_ylabel(...)

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

In my case none of the above solutions worked. I solved by right clicking on the reference

System.Net.Http.Formatting

from Visual studio and setting the property Copy Local to true.

I hope this is useful somehow.

HTML -- two tables side by side

Depending on your content and space, you can use floats or inline display:

<table style="display: inline-block;">

<table style="float: left;">

Check it out here: http://jsfiddle.net/SM769/

Documentation

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

Convert Bitmap to File

Converting Bitmap to File needs to be done in background (NOT IN THE MAIN THREAD) it hangs the UI specially if the bitmap was large

File file;

public class fileFromBitmap extends AsyncTask<Void, Integer, String> {

    Context context;
    Bitmap bitmap;
    String path_external = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";

    public fileFromBitmap(Bitmap bitmap, Context context) {
        this.bitmap = bitmap;
        this.context= context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // before executing doInBackground
        // update your UI
        // exp; make progressbar visible
    }

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

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
        try {
            FileOutputStream fo = new FileOutputStream(file);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        // back to main thread after finishing doInBackground
        // update your UI or take action after
        // exp; make progressbar gone

         sendFile(file);

    }
}

Calling it

new fileFromBitmap(my_bitmap, getApplicationContext()).execute();

you MUST use the file in onPostExecute .

To change directory of file to be stored in cache replace line :

 file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");

with :

file  = new File(context.getCacheDir(), "temporary_file.jpg");

XPath selecting a node with some attribute value equals to some other node's attribute value

I think this is what you want:

/grand/parent/child[@id="#grand"]

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

I think in your case you don't really need a groupby. I would sort by descending order your B column, then drop duplicates at column A and if you want you can also have a new nice and clean index like that:

df.sort_values('B', ascending=False).drop_duplicates('A').sort_index().reset_index(drop=True)

How to checkout a specific Subversion revision from the command line?

You'll have to use svn directly:

svn checkout URL[@REV]... [PATH]

and

svn help co

gives you a little more help.

What is a callback in java

Maybe an example would help.

Your app wants to download a file from some remote computer and then write to to a local disk. The remote computer is the other side of a dial-up modem and a satellite link. The latency and transfer time will be huge and you have other things to do. So, you have a function/method that will write a buffer to disk. You pass a pointer to this method to your network API, together with the remote URI and other stuff. This network call returns 'immediately' and you can do your other stuff. 30 seconds later, the first buffer from the remote computer arrives at the network layer. The network layer then calls the function that you passed during the setup and so the buffer gets written to disk - the network layer has 'called back'. Note that, in this example, the callback would happen on a network layer thread than the originating thread, but that does not matter - the buffer still gets written to the disk.

Android 8: Cleartext HTTP traffic not permitted

It could be useful for someone.

We recently had the same issue for Android 9, but we only needed to display some Urls within WebView, nothing very special. So adding android:usesCleartextTraffic="true" to Manifest worked, but we didn't want to compromise security of the whole app for this. So the fix was in changing links from http to https

What is the recommended way to make a numeric TextField in JavaFX?

Very old thread, but this seems neater and strips out non-numeric characters if pasted.

// force the field to be numeric only
textField.textProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, 
        String newValue) {
        if (!newValue.matches("\\d*")) {
            textField.setText(newValue.replaceAll("[^\\d]", ""));
        }
    }
});

PHP - SSL certificate error: unable to get local issuer certificate

The above steps, though helpful, didnt work for me on Windows 8. I don't know the co-relation, but the below steps worked. Basically a change in the cacert.pem file. Hope this helps someone.

  • Download cacert.pem file from here: http://curl.haxx.se/docs/caextract.html
  • Save the file in your PHP installation folder. (eg: If using xampp – save it in c:\Installation_Dir\xampp\php\cacert.pem).
  • Open your php.ini file and add these lines:
  • curl.cainfo=”C:\Installation_Dir\xampp\php\cacert.pem” openssl.cafile=”C:\Installation_Dir\xampp\php\cacert.pem”
  • Restart your Apache server and that should fix it (Simply stop and start the services as needed).

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

The accepted solution no longer seems to work for newer versions of mysql-python. The installer no longer provides a site.cfg file to edit.

If you are installing mysql-python it'll look for C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include. If you have a 64-bit installation of MySQL, you can simply invoke:

  1. mklink /d "C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" "C:\Program Files\MySQL\MySQL Connector C 6.0.2\include"
  2. Run pip install mysql-python
  3. Delete the symbolic link created in step 1

jquery fill dropdown with json data

In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)

    <script>

        $(document).ready(function(){

            GetData('DLState',data,'stateid','statename');
        });

        var data = [{"stateid" : "1","statename" : "Mumbai"},
                    {"stateid" : "2","statename" : "Panjab"},
                    {"stateid" : "3","statename" : "Pune"},
                     {"stateid" : "4","statename" : "Nagpur"},
                     {"stateid" : "5","statename" : "kanpur"}];

        var Did=document.getElementById("DLState");

        function GetData(Did,data,valkey,textkey){
          var str= "";
          for (var i = 0; i <data.length ; i++){

            console.log(data);


            str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";

          }
          $("#"+Did).append(str);
        };    </script>

</head>
<body>
  <select id="DLState">
  </select>
</body>
</html>

How do you rename a Git tag?

This wiki page has this interesting one-liner, which reminds us that we can push several refs:

git push origin refs/tags/<old-tag>:refs/tags/<new-tag> :refs/tags/<old-tag> && git tag -d <old-tag>

and ask other cloners to do git pull --prune --tags

So the idea is to push:

  • <new-tag> for every commits referenced by <old-tag>: refs/tags/<old-tag>:refs/tags/<new-tag>,
  • the deletion of <old-tag>: :refs/tags/<old-tag>

See as an example "Change naming convention of tags inside a git repository?".

MySQL error 1241: Operand should contain 1 column(s)

Syntax error, remove the ( ) from select.

insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

Loop code for each file in a directory

Looks for the function glob():

<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
    echo $jpg, "\n";
}
?>

Trigger event when user scroll to specific element - with jQuery

You could use this for all devices,

$(document).on('scroll', function() {
    if( $(this).scrollTop() >= $('#target_element').position().top ){
        do_something();
    }
});

Calling virtual functions inside constructors

Calling a polymorphic function from a constructor is a recipe for disaster in most OO languages. Different languages will perform differently when this situation is encountered.

The basic problem is that in all languages the Base type(s) must be constructed previous to the Derived type. Now, the problem is what does it mean to call a polymorphic method from the constructor. What do you expect it to behave like? There are two approaches: call the method at the Base level (C++ style) or call the polymorphic method on an unconstructed object at the bottom of the hierarchy (Java way).

In C++ the Base class will build its version of the virtual method table prior to entering its own construction. At this point a call to the virtual method will end up calling the Base version of the method or producing a pure virtual method called in case it has no implementation at that level of the hierarchy. After the Base has been fully constructed, the compiler will start building the Derived class, and it will override the method pointers to point to the implementations in the next level of the hierarchy.

class Base {
public:
   Base() { f(); }
   virtual void f() { std::cout << "Base" << std::endl; } 
};
class Derived : public Base
{
public:
   Derived() : Base() {}
   virtual void f() { std::cout << "Derived" << std::endl; }
};
int main() {
   Derived d;
}
// outputs: "Base" as the vtable still points to Base::f() when Base::Base() is run

In Java, the compiler will build the virtual table equivalent at the very first step of construction, prior to entering the Base constructor or Derived constructor. The implications are different (and to my likings more dangerous). If the base class constructor calls a method that is overriden in the derived class the call will actually be handled at the derived level calling a method on an unconstructed object, yielding unexpected results. All attributes of the derived class that are initialized inside the constructor block are yet uninitialized, including 'final' attributes. Elements that have a default value defined at the class level will have that value.

public class Base {
   public Base() { polymorphic(); }
   public void polymorphic() { 
      System.out.println( "Base" );
   }
}
public class Derived extends Base
{
   final int x;
   public Derived( int value ) {
      x = value;
      polymorphic();
   }
   public void polymorphic() {
      System.out.println( "Derived: " + x ); 
   }
   public static void main( String args[] ) {
      Derived d = new Derived( 5 );
   }
}
// outputs: Derived 0
//          Derived 5
// ... so much for final attributes never changing :P

As you see, calling a polymorphic (virtual in C++ terminology) methods is a common source of errors. In C++, at least you have the guarantee that it will never call a method on a yet unconstructed object...

Angular 4 img src is not found

AngularJS

<img ng-src="{{imagePath}}">

Angular

<img [src]="imagePath">

Deep copy in ES6 using the spread syntax

Here's my deep copy algorithm.

const DeepClone = (obj) => {
     if(obj===null||typeof(obj)!=='object')return null;
    let newObj = { ...obj };

    for (let prop in obj) {
      if (
        typeof obj[prop] === "object" ||
        typeof obj[prop] === "function"
      ) {
        newObj[prop] = DeepClone(obj[prop]);
      }
    }

    return newObj;
  };

How to make/get a multi size .ico file?

What i do is to prepare a 512x512 PNG, the Alpha Channel is good for rounded corners or drop shadows, then I upload it to this site http://convertico.com/, and for free then it returns me a 6 sizes .ico file with 256x256, 128x128, 64x64, 48x48, 32x32 and 16x16 sizes.

Check if value already exists within list of dictionaries?

Maybe this helps:

a = [{ 'main_color': 'red', 'second_color':'blue'},
     { 'main_color': 'yellow', 'second_color':'green'},
     { 'main_color': 'yellow', 'second_color':'blue'}]

def in_dictlist((key, value), my_dictlist):
    for this in my_dictlist:
        if this[key] == value:
            return this
    return {}

print in_dictlist(('main_color','red'), a)
print in_dictlist(('main_color','pink'), a)

List of foreign keys and the tables they reference in Oracle DB

My version, in my humble opinion, more readable:

SELECT   PARENT.TABLE_NAME  "PARENT TABLE_NAME"
,        PARENT.CONSTRAINT_NAME  "PARENT PK CONSTRAINT"
,       '->' " "
,        CHILD.TABLE_NAME  "CHILD TABLE_NAME"
,        CHILD.COLUMN_NAME  "CHILD COLUMN_NAME"
,        CHILD.CONSTRAINT_NAME  "CHILD CONSTRAINT_NAME"
FROM     ALL_CONS_COLUMNS   CHILD
,        ALL_CONSTRAINTS   CT
,        ALL_CONSTRAINTS   PARENT
WHERE    CHILD.OWNER  =  CT.OWNER
AND      CT.CONSTRAINT_TYPE  = 'R'
AND      CHILD.CONSTRAINT_NAME  =  CT.CONSTRAINT_NAME 
AND      CT.R_OWNER  =  PARENT.OWNER
AND      CT.R_CONSTRAINT_NAME  =  PARENT.CONSTRAINT_NAME 
AND      CHILD.TABLE_NAME  = ::table -- table name variable
AND      CT.OWNER  = ::owner; -- schema variable, could not be needed

Dictionary of dictionaries in Python?

If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:

def addNameToDictionary(d, tup):
    if tup[0] not in d:
        d[tup[0]] = {}
    d[tup[0]][tup[1]] = [tup[2]]

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Determining the current foreground application from a background task or service

i had to figure out the right solution the hard way. the below code is part of cyanogenmod7 (the tablet tweaks) and is tested on android 2.3.3 / gingerbread.

methods:

  • getForegroundApp - returns the foreground application.
  • getActivityForApp - returns the activity of the found app.
  • isStillActive - determines if a earlier found app is still the active app.
  • isRunningService - a helper function for getForegroundApp

this hopefully answers this issue in all extend (:

private RunningAppProcessInfo getForegroundApp() {
    RunningAppProcessInfo result=null, info=null;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
    Iterator <RunningAppProcessInfo> i = l.iterator();
    while(i.hasNext()){
        info = i.next();
        if(info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                && !isRunningService(info.processName)){
            result=info;
            break;
        }
    }
    return result;
}

private ComponentName getActivityForApp(RunningAppProcessInfo target){
    ComponentName result=null;
    ActivityManager.RunningTaskInfo info;

    if(target==null)
        return null;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <ActivityManager.RunningTaskInfo> l = mActivityManager.getRunningTasks(9999);
    Iterator <ActivityManager.RunningTaskInfo> i = l.iterator();

    while(i.hasNext()){
        info=i.next();
        if(info.baseActivity.getPackageName().equals(target.processName)){
            result=info.topActivity;
            break;
        }
    }

    return result;
}

private boolean isStillActive(RunningAppProcessInfo process, ComponentName activity)
{
    // activity can be null in cases, where one app starts another. for example, astro
    // starting rock player when a move file was clicked. we dont have an activity then,
    // but the package exits as soon as back is hit. so we can ignore the activity
    // in this case
    if(process==null)
        return false;

    RunningAppProcessInfo currentFg=getForegroundApp();
    ComponentName currentActivity=getActivityForApp(currentFg);

    if(currentFg!=null && currentFg.processName.equals(process.processName) &&
            (activity==null || currentActivity.compareTo(activity)==0))
        return true;

    Slog.i(TAG, "isStillActive returns false - CallerProcess: " + process.processName + " CurrentProcess: "
            + (currentFg==null ? "null" : currentFg.processName) + " CallerActivity:" + (activity==null ? "null" : activity.toString())
            + " CurrentActivity: " + (currentActivity==null ? "null" : currentActivity.toString()));
    return false;
}

private boolean isRunningService(String processname){
    if(processname==null || processname.isEmpty())
        return false;

    RunningServiceInfo service;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <RunningServiceInfo> l = mActivityManager.getRunningServices(9999);
    Iterator <RunningServiceInfo> i = l.iterator();
    while(i.hasNext()){
        service = i.next();
        if(service.process.equals(processname))
            return true;
    }

    return false;
}

Different names of JSON property during serialization and deserialization

I would bind two different getters/setters pair to one variable:

class Coordinates{
    int red;

    @JsonProperty("red")
    public byte getRed() {
      return red;
    }

    public void setRed(byte red) {
      this.red = red;
    }

    @JsonProperty("r")
    public byte getR() {
      return red;
    }

    public void setR(byte red) {
      this.red = red;
    }
}

Upload DOC or PDF using PHP

For application/msword and application/vnd.ms-excel, when I deleted the size restriction:

($_FILES["file"]["size"] < 20000)

...it worked ok.

How to remove illegal characters from path and filenames?

public static bool IsValidFilename(string testName)
{
    return !new Regex("[" + Regex.Escape(new String(System.IO.Path.GetInvalidFileNameChars())) + "]").IsMatch(testName);
}

How to copy a string of std::string type in C++?

strcpy example:

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

int main ()
{
  char str1[]="Sample string" ;
  char str2[40] ;
  strcpy (str2,str1) ;
  printf ("str1: %s\n",str1) ;
  return 0 ;
}

Output: str1: Sample string

Your case:

A simple = operator should do the job.

string str1="Sample string" ;
string str2 = str1 ;

Using Helvetica Neue in a Website

Assuming you have referenced and correctly integrated your font to your site (presumably using an @font-face kit) it should be alright to just reference yours the way you do. Presumably it is like this so they have fall backs incase some browsers do not render the fonts correctly

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

I change the input type on my checkbox, so on my OnCheckedChangeListener i do:

passwordEdit.setInputType(InputType.TYPE_CLASS_TEXT| (isChecked? InputType.TYPE_TEXT_VARIATION_PASSWORD|~InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD));

And it finally worked.

Seems like a boolean problem with TYPE_TEXT_VARIATION_VISIBLE_PASSWORD. Invert the flag and it should fix the problem.

In your case:

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD|~InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

Ruby on Rails form_for select field with class

This work for me

<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>

How to make an AlertDialog in Flutter?

One Button

showAlertDialog(BuildContext context) {

  // set up the button
  Widget okButton = FlatButton(
    child: Text("OK"),
    onPressed: () { },
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("My title"),
    content: Text("This is my message."),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Two Buttons

showAlertDialog(BuildContext context) {

  // set up the buttons
  Widget cancelButton = FlatButton(
    child: Text("Cancel"),
    onPressed:  () {},
  );
  Widget continueButton = FlatButton(
    child: Text("Continue"),
    onPressed:  () {},
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("AlertDialog"),
    content: Text("Would you like to continue learning how to use Flutter alerts?"),
    actions: [
      cancelButton,
      continueButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Three Buttons

showAlertDialog(BuildContext context) {

  // set up the buttons
  Widget remindButton = FlatButton(
    child: Text("Remind me later"),
    onPressed:  () {},
  );
  Widget cancelButton = FlatButton(
    child: Text("Cancel"),
    onPressed:  () {},
  );
  Widget launchButton = FlatButton(
    child: Text("Launch missile"),
    onPressed:  () {},
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("Notice"),
    content: Text("Launching this missile will destroy the entire universe. Is this what you intended to do?"),
    actions: [
      remindButton,
      cancelButton,
      launchButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Handling button presses

The onPressed callback for the buttons in the examples above were empty, but you could add something like this:

Widget launchButton = FlatButton(
  child: Text("Launch missile"),
  onPressed:  () {
    Navigator.of(context).pop(); // dismiss dialog
    launchMissile();
  },
);

If you make the callback null, then the button will be disabled.

onPressed: null,

enter image description here

Supplemental code

Here is the code for main.dart in case you weren't getting the functions above to run.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter'),
        ),
        body: MyLayout()),
    );
  }
}

class MyLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: RaisedButton(
        child: Text('Show alert'),
        onPressed: () {
          showAlertDialog(context);
        },
      ),
    );
  }
}

// replace this function with the examples above
showAlertDialog(BuildContext context) { ... }

Get filename in batch for loop

If you want to remain both filename (only) and extension, you may use %~nxF:

FOR /R C:\Directory %F in (*.*) do echo %~nxF

How do I get the key at a specific index from a Dictionary in Swift?

I was looking for something like a LinkedHashMap in Java. Neither Swift nor Objective-C have one if I'm not mistaken.

My initial thought was to wrap my dictionary in an Array. [[String: UIImage]] but then I realized that grabbing the key from the dictionary was wacky with Array(dict)[index].key so I went with Tuples. Now my array looks like [(String, UIImage)] so I can retrieve it by tuple.0. No more converting it to an Array. Just my 2 cents.

Default value in Doctrine

You can do it using xml as well:

<field name="acmeOne" type="string" column="acmeOne" length="36">
    <options>
        <option name="comment">Your SQL field comment goes here.</option>
        <option name="default">Default Value</option>
    </options>
</field>

What is the meaning of @_ in Perl?

First hit of a search for perl @_ says this:

@_ is the list of incoming parameters to a sub.

It also has a longer and more detailed explanation of the same.

How to get the month name in C#?

Supposing your date is today. Hope this helps you.

DateTime dt = DateTime.Today;

string thisMonth= dt.ToString("MMMM");

Console.WriteLine(thisMonth);

How to decrease prod bundle size?

One thing I wish to share is how imported libraries increase the size of the dist. I had angular2-moment package imported, whereas I could do all the date time formatting I required using the standard DatePipe exported from @angular/common.

With Angular2-Moment "angular2-moment": "^1.6.0",

chunk {0} polyfills.036982dc15bb5fc67cb8.bundle.js (polyfills) 191 kB {4} [initial] [rendered] chunk {1} main.e7496551a26816427b68.bundle.js (main) 2.2 MB {3} [initial] [rendered] chunk {2} styles.056656ed596d26ba0192.bundle.css (styles) 69 bytes {4} [initial] [rendered] chunk {3} vendor.62c2cfe0ca794a5006d1.bundle.js (vendor) 3.84 MB [initial] [rendered] chunk {4} inline.0b9c3de53405d705e757.bundle.js (inline) 0 bytes [entry] [rendered]

After removing Angular2-moment and using DatePipe instead

chunk {0} polyfills.036982dc15bb5fc67cb8.bundle.js (polyfills) 191 kB {4} [initial] [rendered] chunk {1} main.f2b62721788695a4655c.bundle.js (main) 2.2 MB {3} [initial] [rendered] chunk {2} styles.056656ed596d26ba0192.bundle.css (styles) 69 bytes {4} [initial] [rendered] chunk {3} vendor.e1de06303258c58c9d01.bundle.js (vendor) 3.35 MB [initial] [rendered] chunk {4} inline.3ae24861b3637391ba70.bundle.js (inline) 0 bytes [entry] [rendered]

Note the vendor bundle has reduced half a Megabyte!

Point is it is worth checking what angular standard packages can do even if you are already familiar with an external lib.

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the maximum possible length of a query string?

Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.

Please see the below example code for Windows IIS Servers with Web.config:

<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxQueryString="1024" maxUrl="2048">
           <headerLimits>
              <add header="Content-type" sizeLimit="100" />
           </headerLimits>
        </requestLimits>
     </requestFiltering>
</security>
</system.webServer>

This would also work on a server level using machine.config.

Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.

json parsing error syntax error unexpected end of input

Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz" but only sees "abcd...wxy.

This can be a typo error somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.

One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage:

chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
    console.log(data);
});

Now before your callback is called, the browser would attempt to parse the message using JSON.parse which can give you "unexpected end of input" errors if the supplied byte length does not match the data.

Angular 2: How to style host element of the component?

Check out this issue. I think the bug will be resolved when new template precompilation logic will be implemented. For now I think the best you can do is to wrap your template into <div class="root"> and style this div:

@Component({ ... })
@View({
  template: `
    <div class="root">
      <h2>Hello Angular2!</h2>
      <p>here is your template</p>
    </div>
  `,
  styles: [`
    .root {
      background: blue;
    }
  `],
   ...
})
class SomeComponent {}

See this plunker

fatal error LNK1169: one or more multiply defined symbols found in game programming

just add /FORCE as linker flag and you're all set.

for instance, if you're working on CMakeLists.txt. Then add following line:

SET(CMAKE_EXE_LINKER_FLAGS  "/FORCE")

Creation timestamp and last update timestamp with Hibernate and MySQL

As data type in JAVA I strongly recommend to use java.util.Date. I ran into pretty nasty timezone problems when using Calendar. See this Thread.

For setting the timestamps I would recommend using either an AOP approach or you could simply use Triggers on the table (actually this is the only thing that I ever find the use of triggers acceptable).

pod install -bash: pod: command not found

@Babul Prabhakar was right

IMPORTANT: However,if you still get "pod: command not found" after using his solution, this command could solve your problem:

sudo chown -R $(whoami):admin /usr/local

How to print the number of characters in each line of a text file

Try this:

while read line    
do    
    echo -e |wc -m      
done <abc.txt    

How to set an HTTP proxy in Python 2.7?

For installing pip with get-pip.py behind a proxy I went with the steps below. My server was even behind a jump server.

From the jump server:

ssh -R 18080:proxy-server:8080 my-python-server

On the "python-server"

export https_proxy=https://localhost:18080 ; export http_proxy=http://localhost:18080 ; export ftp_proxy=$http_proxy
python get-pip.py

Success.

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Correct way of looping through C++ arrays

Add a stopping value to the array:

#include <iostream>
using namespace std;

int main ()
{
   string texts[] = {"Apple", "Banana", "Orange", ""};
   for( unsigned int a = 0; texts[a].length(); a = a + 1 )
   {
       cout << "value of a: " << texts[a] << endl;
   }

   return 0;
}

C++ preprocessor __VA_ARGS__ number of arguments

herein a simple way to count 0 or more arguments of VA_ARGS, my exemple assumes a maximum of 5 variables, but you can add more if you want.

#define VA_ARGS_NUM_PRIV(P1, P2, P3, P4, P5, P6, Pn, ...) Pn
#define VA_ARGS_NUM(...) VA_ARGS_NUM_PRIV(-1, ##__VA_ARGS__, 5, 4, 3, 2, 1, 0)


VA_ARGS_NUM()      ==> 0
VA_ARGS_NUM(19)    ==> 1
VA_ARGS_NUM(9, 10) ==> 2
         ...

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

The COLLATE keyword specify what kind of character set and rules (order, confrontation rules) you are using for string values.

For example in your case you are using Latin rules with case insensitive (CI) and accent sensitive (AS)

You can refer to this Documentation

Span inside anchor or anchor inside span or doesn't matter?

Personally, as a web developer, I only ever put a span within an anchor tag if I am trying to highlight a section of the links text, such as applying a background to one section.

MSIE and addEventListener Problem in Javascript?

The problem is that IE does not have the standard addEventListener method. IE uses its own attachEvent which does pretty much the same.

Good explanation of the differences, and also about the 3rd parameter can be found at quirksmode.

MySQL - Make an existing Field Unique

ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

is the right answer

the insert part

INSERT IGNORE INTO mytable ....

How to detect if a browser is Chrome using jQuery?

userAgent can be changed. for more robust, use the global variable specified by chrome

$.browser.chrome = (typeof window.chrome === "object");

Fast check for NaN in NumPy

If you're comfortable with it allows to create a fast short-circuit (stops as soon as a NaN is found) function:

import numba as nb
import math

@nb.njit
def anynan(array):
    array = array.ravel()
    for i in range(array.size):
        if math.isnan(array[i]):
            return True
    return False

If there is no NaN the function might actually be slower than np.min, I think that's because np.min uses multiprocessing for large arrays:

import numpy as np
array = np.random.random(2000000)

%timeit anynan(array)          # 100 loops, best of 3: 2.21 ms per loop
%timeit np.isnan(array.sum())  # 100 loops, best of 3: 4.45 ms per loop
%timeit np.isnan(array.min())  # 1000 loops, best of 3: 1.64 ms per loop

But in case there is a NaN in the array, especially if it's position is at low indices, then it's much faster:

array = np.random.random(2000000)
array[100] = np.nan

%timeit anynan(array)          # 1000000 loops, best of 3: 1.93 µs per loop
%timeit np.isnan(array.sum())  # 100 loops, best of 3: 4.57 ms per loop
%timeit np.isnan(array.min())  # 1000 loops, best of 3: 1.65 ms per loop

Similar results may be achieved with Cython or a C extension, these are a bit more complicated (or easily avaiable as bottleneck.anynan) but ultimatly do the same as my anynan function.

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

PYTHON 3

import urllib.request

wp = urllib.request.urlopen("http://example.com")

pw = wp.read()

print(pw)

PYTHON 2

import urllib

 import sys

 wp = urllib.urlopen("http://example.com")

 for line in wp:

     sys.stdout.write(line)

While I have tested both the Codes in respective versions.

Why can't I have abstract static methods in C#?

We actually override static methods (in delphi), it's a bit ugly, but it works just fine for our needs.

We use it so the classes can have a list of their available objects without the class instance, for example, we have a method that looks like this:

class function AvailableObjects: string; override;
begin
  Result := 'Object1, Object2';
end; 

It's ugly but necessary, this way we can instantiate just what is needed, instead of having all the classes instantianted just to search for the available objects.

This was a simple example, but the application itself is a client-server application which has all the classes available in just one server, and multiple different clients which might not need everything the server has and will never need an object instance.

So this is much easier to maintain than having one different server application for each client.

Hope the example was clear.

pip installing in global site-packages instead of virtualenv

I have to use 'sudo' for installing packages through pip on my ubuntu system for some reason. This is causing the packages to be installed in global site-packages. Putting this here for anyone who might face this issue in future.

how to insert value into DataGridView Cell?

For Some Reason I could Not add Numbers(in string Format) to the DataGridView But This Worked For Me Hope it help someone!

//dataGridView1.Rows[RowCount].Cells[0].Value = FEString3;//This was not adding Stringed Numbers like "1","2","3"....
DataGridViewCell NewCell = new DataGridViewTextBoxCell();//Create New Cell
NewCell.Value = FEString3;//Set Cell Value
DataGridViewRow NewRow = new DataGridViewRow();//Create New Row
NewRow.Cells.Add(NewCell);//Add Cell to Row
dataGridView1.Rows.Add(NewRow);//Add Row To Datagrid

Marker content (infoWindow) Google Maps

We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:

Create a new function with your information for the infoWindow in it:

function addInfoWindow(marker, message) {

            var infoWindow = new google.maps.InfoWindow({
                content: message
            });

            google.maps.event.addListener(marker, 'click', function () {
                infoWindow.open(map, marker);
            });
        }

Then call the function with the array ID and the marker you want to create:

addInfoWindow(marker, hotels[i][3]);

Change Bootstrap input focus blue glow

You can use the .form-control selector to match all inputs. For example to change to red:

.form-control:focus {
  border-color: #FF0000;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}

Put it in your custom css file and load it after bootstrap.css. It will apply to all inputs including textarea, select etc...

C++ variable has initializer but incomplete type?

Sometimes, the same error occurs when you forget to include the corresponding header.

Removing duplicate values from a PowerShell array

With my method you can completely remove duplicate values, leaving you with values from the array that only had a count of 1. It was not clear if this is what the OP actually wanted however I was unable to find an example of this solution online so here it is.

$array=@'
Bananna
Apple
Carrot
Pear
Apricot
Pear
Bananna
'@ -split '\r\n'

($array | Group-Object -NoElement | ?{$_.count -eq 1}).Name

Make more than one chart in same IPython Notebook cell

You can also call the show() function after each plot. e.g

   plt.plot(a)
   plt.show()
   plt.plot(b)
   plt.show()

Get list of data-* attributes using javascript / jQuery

I use nested each - for me this is the easiest solution (Easy to control/change "what you do with the values - in my example output data-attributes as ul-list) (Jquery Code)

_x000D_
_x000D_
var model = $(".model");_x000D_
_x000D_
var ul = $("<ul>").appendTo("body");_x000D_
_x000D_
$(model).each(function(index, item) {_x000D_
  ul.append($(document.createElement("li")).text($(this).text()));_x000D_
  $.each($(this).data(), function(key, value) {_x000D_
    ul.append($(document.createElement("strong")).text(key + ": " + value));_x000D_
    ul.append($(document.createElement("br")));_x000D_
  }); //inner each_x000D_
  ul.append($(document.createElement("hr")));_x000D_
}); // outer each_x000D_
_x000D_
/*print html*/_x000D_
var htmlString = $("ul").html();_x000D_
$("code").text(htmlString);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/prism.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/themes/prism-okaidia.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<h1 id="demo"></h1>_x000D_
_x000D_
<ul>_x000D_
  <li class="model" data-price="45$" data-location="Italy" data-id="1234">Model 1</li>_x000D_
  <li class="model" data-price="75$" data-location="Israel" data-id="4321">Model 2</li> _x000D_
  <li class="model" data-price="99$" data-location="France" data-id="1212">Model 3</li> _x000D_
</ul>_x000D_
_x000D_
<pre>_x000D_
<code class="language-html">_x000D_
  _x000D_
</code>_x000D_
</pre>_x000D_
_x000D_
<h2>Generate list by code</h2>_x000D_
<br>
_x000D_
_x000D_
_x000D_

Codepen: https://codepen.io/ezra_siton/pen/GRgRwNw?editors=1111

z-index not working with fixed positioning

Add position: relative; to #over

_x000D_
_x000D_
    #over {_x000D_
      width: 600px;_x000D_
      z-index: 10;_x000D_
      position: relative;    _x000D_
    }_x000D_
    _x000D_
    #under {_x000D_
      position: fixed;_x000D_
      top: 5px;_x000D_
      width: 420px;_x000D_
      left: 20px;_x000D_
      border: 1px solid;_x000D_
      height: 10%;_x000D_
      background: #fff;_x000D_
      z-index: 1;_x000D_
    }
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    <body>_x000D_
     <div id="over">_x000D_
      Hello Hello HelloHelloHelloHelloHello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello_x000D_
     </div>  _x000D_
    _x000D_
     <div id="under"></div>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Fiddle

Angular 5 Reactive Forms - Radio Button Group

I tried your code, you didn't assign/bind a value to your formControlName.

In HTML file:

<form [formGroup]="form">
   <label>
     <input type="radio" value="Male" formControlName="gender">
       <span>male</span>
   </label>
   <label>
     <input type="radio" value="Female" formControlName="gender">
       <span>female</span>
   </label>
</form>

In the TS file:

  form: FormGroup;
  constructor(fb: FormBuilder) {
    this.name = 'Angular2'
    this.form = fb.group({
      gender: ['', Validators.required]
    });
  }

Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

See the screenshot: enter image description here

To make it shorter:

<form [formGroup]="form">
  <input type="radio" value='Male' formControlName="gender" >Male
  <input type="radio" value='Female' formControlName="gender">Female
</form>

enter image description here

Hope it helps:)

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

Delete node_modules

rm -r node_modules

install packages again

npm install

addEventListener for keydown on Canvas

encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.

How do I use MySQL through XAMPP?

XAMPP Apache + MariaDB + PHP + Perl (X -any OS)

  • After successful installation execute xampp-control.exe in XAMPP folder
  • Start Apache and MySQL enter image description here

  • Open browser and in url type localhost or 127.0.0.1

  • then you are welcomed with dashboard

By default your port is listing with 80.If you want you can change it to your desired port number in httpd.conf file.(If port 80 is already using with other app then you have to change it).

For example you changed port number 80 to 8090 then you can run as 'localhost:8090' or '127.0.0.1:8090'

Import Python Script Into Another?

Hope this work

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.pop(0)
    print (word)

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print(word)

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)


print ("Let's practice everything.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""


print ("--------------")
print (poem)
print ("--------------")

five = 10 - 2 + 3 - 5
print ("This should be five: %s" % five)

def secret_formula(start_point):
    jelly_beans = start_point * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
jelly_beans, jars, crates = secret_formula(start_point)

print ("With a starting point of: %d" % start_point)
print ("We'd have %d jeans, %d jars, and %d crates." % (jelly_beans, jars, crates))

start_point = start_point / 10

print ("We can also do that this way:")
print ("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))


sentence = "All god\tthings come to those who weight."

words =  break_words(sentence)
sorted_words =  sort_words(words)

print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words =  sort_sentence(sentence)
print (sorted_words)

print_first_and_last(sentence)
print_first_and_last_sorted(sentence)

Does VBA contain a comment block syntax?

prefix the comment with a single-quote. there is no need for an "end" tag.

'this is a comment

Extend to multiple lines using the line-continuation character, _:

'this is a multi-line _
   comment

This is an option in the toolbar to select a line(s) of code and comment/uncomment:

enter image description here

Java - Opposite of .contains (does not contain)

Maybe

if (inventory.contains("bread") && !inventory.contains("water"))

Or

if (inventory.contains("bread")) {
    if (!inventory.contains("water")) {
        // do something here
    } 
}

Loading basic HTML in Node.js

How about using express module?

    var app = require('express')();

    app.get('/',function(request,response){
       response.sendFile(__dirname+'/XXX.html');
    });

    app.listen('8000');

then, you can use browser to get /localhost:8000

Grant SELECT on multiple tables oracle

No. As the documentation shows, you can only grant access to one object at a time.

Issue with Task Scheduler launching a task

I solved the issue by opening up the properties on the exe-file itself. On the tab Compatibility there's a check box for privilege level that says "Run this as an administrator"

Even though my account have administration privileges it didn't work when I started it from task scheduler.

I unchecked the box and started it from the scheduler again and it worked.

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

In my case i just went through following steps in windows 10.

  1. goto control panel
  2. click administrative
  3. click services
  4. find OracelServeceXE, OracleXEClrAgeng, OracleXETNSListener
  5. Right click and press Start/Restart
  6. After Completing Process. Check it will work or it will work ;)
  7. Done
  8. All the Best.

Passing capturing lambda as function pointer

A shortcut for using a lambda with as a C function pointer is this:

"auto fun = +[](){}"

Using Curl as exmample (curl debug info)

auto callback = +[](CURL* handle, curl_infotype type, char* data, size_t size, void*){ //add code here :-) };
curl_easy_setopt(curlHande, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curlHande,CURLOPT_DEBUGFUNCTION,callback);

Undefined symbols for architecture arm64

In my case, I had to look for

C++ Standard Library and make sure that the libc++ was the one selected.

What is the difference between `Enum.name()` and `Enum.toString()`?

The main difference between name() and toString() is that name() is a final method, so it cannot be overridden. The toString() method returns the same value that name() does by default, but toString() can be overridden by subclasses of Enum.

Therefore, if you need the name of the field itself, use name(). If you need a string representation of the value of the field, use toString().

For instance:

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;

    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase();
    }
}

In this example, WeekDay.MONDAY.name() returns "MONDAY", and WeekDay.MONDAY.toString() returns "Monday".

WeekDay.valueOf(WeekDay.MONDAY.name()) returns WeekDay.MONDAY, but WeekDay.valueOf(WeekDay.MONDAY.toString()) throws an IllegalArgumentException.

Java Project: Failed to load ApplicationContext

I had the same problem, and I was using the following plugin for tests:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <useFile>true</useFile>
        <includes>
            <include>**/*Tests.java</include>
            <include>**/*Test.java</include>
        </includes>
        <excludes>
            <exclude>**/Abstract*.java</exclude>
        </excludes>
        <junitArtifactName>junit:junit</junitArtifactName>
        <parallel>methods</parallel>
        <threadCount>10</threadCount>
    </configuration>
</plugin>

The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.

After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:

    <parallel>methods</parallel>
    <threadCount>10</threadCount>

Hope that this helps someone out!

Solving "adb server version doesn't match this client" error

This issue for me was caused by having apowermirror running at the same time, from what I can tell any software that could use a different version of adb could cause these issues as others mention in this thread this can include Genymotion or from other threads unreal studio was the problem.

get string value from HashMap depending on key name

Suppose you declared HashMap as :-

HashMap<Character,Integer> hs = new HashMap<>();

Then,key in map is of type Character data type and value of int type.Now,to get value corresponding to key irrespective of type of key,value type, syntax is :-

    char temp = 'a';
    if(hs.containsKey(temp)){
`       int val = hs.get(temp); //val is the value corresponding to key temp
    }

So, according to your question you want to get string value corresponding to a key.For this, just declare HashMap as HashMap<"datatype of key","datatype of value" hs = new HashMap<>(); Using this will make your code cleaner and also you don't have to convert the result of hs.get("my_code") to string as by default it returns value of string if at entry time one has kept value as a string.

Delete entire row if cell contains the string X

Try this ...

Dim r as Range
Dim x as Integer

For x = 5000 to 4 step -1 '---> or change as you want //Thanx 4 KazJaw

  set r = range("E" & format(x))
  if ucase(r.Value) = "NONE" then
    Rows(x).EntireRow.Delete
  end if 

Next

When should I use nil and NULL in Objective-C?

NULL and nil are equal to each other, but nil is an object value while NULL is a generic pointer value ((void*)0, to be specific). [NSNull null] is an object that's meant to stand in for nil in situations where nil isn't allowed. For example, you can't have a nil value in an NSArray. So if you need to represent a "nil", you can use [NSNull null].

Current date and time as string

Using C++ in MS Visual Studio 2015 (14), I use:

#include <chrono>

string NowToString()
{
  chrono::system_clock::time_point p = chrono::system_clock::now();
  time_t t = chrono::system_clock::to_time_t(p);
  char str[26];
  ctime_s(str, sizeof str, &t);
  return str;
}

How to force Selenium WebDriver to click on element which is not currently visible?

There are many good answers on this page.

  1. I typically start with maximize.window(), actually I do this in the driver Factory or wherever you initialize your driver. This is something done by default - always.
  2. Its usually a wait for element because of some javascript delay.

Both are discussed in various details above. The answer I didn't see was ScrollToElement. It sounds like you are processing a list of elements, while processing you are creating more elements, checkboxes. This can cause elements in your list to move off the visible page. Sometimes you can see the element with the naked eye but you just can't click on it. When processing lists you sometimes have to interject scrolling.

  • Set a break point and check to see if the element you are using is at the window edge, top/bottom right/left. Sometimes when this is the case you can't get to it via selenium but you can manually click with your mouse.

Because I run across this I created a PageScroll.java and put my scrolling scripts there. Here are a few of the methods from this class:

public static void scrollToTop(WebDriver driver) {
      ((JavascriptExecutor) driver)
        .executeScript("window.scrollTo(0,0)");
    }

    public static void scrollToBottom(WebDriver driver) {
      ((JavascriptExecutor) driver)
        .executeScript("window.scrollTo(0, document.body.scrollHeight)");
    }

    public static void scrollToElementTop(WebDriver driver, WebElement element) {
      ((JavascriptExecutor) driver).executeScript(
        "arguments[0].scrollIntoView(true);", element);
    }

    public static void scrollToElementBottom(WebDriver driver, WebElement element) {
      ((JavascriptExecutor) driver).executeScript(
        "arguments[0].scrollIntoView(false);", element);
    }

see Scroll Element into View with Selenium for more examples

Getting error: ISO C++ forbids declaration of with no type

Your declaration is int ttTreeInsert(int value);

However, your definition/implementation is

ttTree::ttTreeInsert(int value)
{
}

Notice that the return type int is missing in the implementation. Instead it should be

int ttTree::ttTreeInsert(int value)
{
    return 1; // or some valid int
}

add title attribute from css

Quentin is correct, it can't be done with CSS. If you want to add a title attribute, you can do it with JavaScript. Here's an example using jQuery:

$('label').attr('title','mandatory');

What is the difference between Numpy's array() and asarray() functions?

Here's a simple example that can demonstrate the difference.

The main difference is that array will make a copy of the original data and using different object we can modify the data in the original array.

import numpy as np
a = np.arange(0.0, 10.2, 0.12)
int_cvr = np.asarray(a, dtype = np.int64)

The contents in array (a), remain untouched, and still, we can perform any operation on the data using another object without modifying the content in original array.

Assign output of a program to a variable using a MS batch file

As an addition to this previous answer, pipes can be used inside a for statement, escaped by a caret symbol:

    for /f "tokens=*" %%i in ('tasklist ^| grep "explorer"') do set VAR=%%i

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

That's not the right way to set the permissions as you are overwriting them with each method call.

Replace this:

mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.setReadPermissions("public_profile");
mButtonLogin.setReadPermissions("email");
mButtonLogin.setReadPermissions("user_birthday");

With the following, as the method setReadPermissions() accepts an ArrayList:

loginButton.setReadPermissions(Arrays.asList(
        "public_profile", "email", "user_birthday", "user_friends"));

Also here is how to query extra data GraphRequest:

private LoginButton loginButton;
private CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setReadPermissions(Arrays.asList(
            "public_profile", "email", "user_birthday", "user_friends"));

    callbackManager = CallbackManager.Factory.create();

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("LoginActivity", response.toString());

                            // Application code
                            String email = object.getString("email");
                            String birthday = object.getString("birthday"); // 01/31/1980 format
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender,birthday");
            request.setParameters(parameters);
            request.executeAsync();


        }

        @Override
        public void onCancel() {
            // App code
            Log.v("LoginActivity", "cancel");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.v("LoginActivity", exception.getCause().toString());
        }
    });
}

EDIT:

One possible problem is that Facebook assumes that your email is invalid. To test it, use the Graph API Explorer and try to get it. If even there you can't get your email, change it in your profile settings and try again. This approach resolved this issue for some developers commenting my answer.

Changing the maximum length of a varchar column?

ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME VARCHAR(40);

Late to the question - but I am using Oracle SQL Developer and @anonymous's answer was the closest but kept receiving syntax errors until I edited the query to this.

Hope this helps someone

Swift: How to get substring from start to last index of character

String has builtin substring feature:

extension String : Sliceable {
    subscript (subRange: Range<String.Index>) -> String { get }
}

If what you want is "going to the first index of a character", you can get the substring using builtin find() function:

var str = "www.stackexchange.com"
str[str.startIndex ..< find(str, ".")!] // -> "www"

To find last index, we can implement findLast().

/// Returns the last index where `value` appears in `domain` or `nil` if
/// `value` is not found.
///
/// Complexity: O(\ `countElements(domain)`\ )
func findLast<C: CollectionType where C.Generator.Element: Equatable>(domain: C, value: C.Generator.Element) -> C.Index? {
    var last:C.Index? = nil
    for i in domain.startIndex..<domain.endIndex {
        if domain[i] == value {
            last = i
        }
    }
    return last
}

let str = "www.stackexchange.com"
let substring = map(findLast(str, ".")) { str[str.startIndex ..< $0] } // as String?
// if "." is found, substring has some, otherwise `nil`

ADDED:

Maybe, BidirectionalIndexType specialized version of findLast is faster:

func findLast<C: CollectionType where C.Generator.Element: Equatable, C.Index: BidirectionalIndexType>(domain: C, value: C.Generator.Element) -> C.Index? {
    for i in lazy(domain.startIndex ..< domain.endIndex).reverse() {
        if domain[i] == value {
            return i
        }
    }
    return nil
}

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

Notice: Undefined offset: 0 in

As you might have already about knew the error. This is due to trying to access the empty array or trying to access the value of empty key of array. In my project, I am dealing with this error with counting the array and displaying result.

You can do it like this:

if(count($votes) == '0'){

    echo 'Sorry, no votes are available at the moment.';
}
else{
    //do the stuff with votes
}

count($votes) counts the $votes array. If it is equal to zero (0), you can display your custom message or redirect to certain page else you can do stuff with $votes. In this way you can remove the Notice: Undefined offset: 0 in notice in PHP.

Open Cygwin at a specific folder

For cygwin64 or installations without chere you can use the following command in a registry entry (assuming windows due to your path, also assuming cygwin installation directory is c:\cygwin64)

C:\cygwin64\bin\mintty.exe /bin/sh -lc 'cd "`cygpath "%V"`"; bash'

Works on Windows 7 and 8 Registry file available for download here: http://tomkay.me/blog/Cygwin64---Open-Here-18

Windows Registry Editor Version 5.00
; Open cygwin to folder
; http://tomkay.me - Tom Kay

[HKEY_CLASSES_ROOT\Folder\shell\open_cygwin]
@="Open Cygwin Here"

[HKEY_CLASSES_ROOT\Folder\shell\open_cygwin\command]
@="C:\\cygwin64\\bin\\mintty.exe /bin/sh -lc 'cd \"`cygpath \"%V\"`\"; bash'"

[HKEY_CLASSES_ROOT\Directory\Background\shell\open_cygwin]
@="Open Cygwin Here"

[HKEY_CLASSES_ROOT\Directory\Background\shell\open_cygwin\command]
@="C:\\cygwin64\\bin\\mintty.exe /bin/sh -lc 'cd \"`cygpath \"%V\"`\"; bash'"

How do I divide so I get a decimal value?

Don't worry about it. In your code, just do the separate / and % operations as you mention, even though it might seem like it's inefficient. Let the JIT compiler worry about combining these operations to get both quotient and remainder in a single machine instruction (as far as I recall, it generally does).