Programs & Examples On #Httpforbiddenhandler

Java: How to stop thread?

The recommended way will be to build this into the thread. So no you can't (or rather shouldn't) kill the thread from outside.

Have the thread check infrequently if it is required to stop. (Instead of blocking on a socket until there is data. Use a timeout and every once in a while check if the user indicated wanting to stop)

How to Cast Objects in PHP

Without using inheritance (as mentioned by author), it seems like you are looking for a solution that can transform one class to another with preassumption of the developer knows and understand the similarity of 2 classes.

There's no existing solution for transforming between objects. What you can try out are:

Java escape JSON String?

Try to replace all the " and ' with a \ before them. Do this just for the msget object(String, I guess). Don't forget that \ must be escaped too.

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

.parent {
    margin:0 auto;
    width:700px;
    border:2px solid red;
}
.child {
    position:absolute;
    width:100%;
    border:2px solid blue;
    left:0;
    top:200px;
}

How to create a template function within a class? (C++)

See here: Templates, template methods,Member Templates, Member Function Templates

class   Vector
{
  int     array[3];

  template <class TVECTOR2> 
  void  eqAdd(TVECTOR2 v2);
};

template <class TVECTOR2>
void    Vector::eqAdd(TVECTOR2 a2)
{
  for (int i(0); i < 3; ++i) array[i] += a2[i];
}

How can I get all the request headers in Django?

For what it's worth, it appears your intent is to use the incoming HTTP request to form another HTTP request. Sort of like a gateway. There is an excellent module django-revproxy that accomplishes exactly this.

The source is a pretty good reference on how to accomplish what you are trying to do.

C#: How to access an Excel cell?

If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)

Check this out, it should get you started,

http://www.codeproject.com/KB/office/package.aspx

And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.

Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;

if ( sheet != null )
{
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    if ( range != null )
    {
        int nRows = usedRange.Rows.Count;
        int nCols = usedRange.Columns.Count;
        foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
        {
            string value = row.Cells[0].FormattedValue as string;
        }
    }
 }

You can also do

Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;

if ( sheets != null )
{
     foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
     {
          // Do Stuff
     }
}

And if you need to insert rows/columns

// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );

how to load CSS file into jsp

You can write like that. This is for whenever you change context path you don't need to modify your jsp file.

<link rel="stylesheet" href="${pageContext.request.contextPath}/css/styles.css" />

Angular cookies

Update: angular2-cookie is now deprecated. Please use my ngx-cookie instead.

Old answer:

Here is angular2-cookie which is the exact implementation of Angular 1 $cookies service (plus a removeAll() method) that I created. It is using the same methods, only implemented in typescript with Angular 2 logic.

You can inject it as a service in the components providers array:

import {CookieService} from 'angular2-cookie/core';

@Component({
    selector: 'my-very-cool-app',
    template: '<h1>My Angular2 App with Cookies</h1>',
    providers: [CookieService]
})

After that, define it in the consturctur as usual and start using:

export class AppComponent { 
  constructor(private _cookieService:CookieService){}

  getCookie(key: string){
    return this._cookieService.get(key);
  }
}

You can get it via npm:

npm install angular2-cookie --save

Attach IntelliJ IDEA debugger to a running Java process

Also, don't forget you need to add "-Xdebug" flag in app JAVA_OPTS if you want connect in debug mode.

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

How to remove a column from an existing table?

This is the correct answer:

ALTER TABLE MEN DROP COLUMN Lname

But... if a CONSTRAINT exists on the COLUMN, then you must DROP the CONSTRAINT first, then you will be able to DROP the COLUMN. In order to drop a CONSTRAINT, run:

ALTER TABLE MEN DROP CONSTRAINT {constraint_name_on_column_Lname}

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.

To trigger an event after ng-repeat has rendered try this directive:

var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
    restrict: 'A',
    link: function (scope, element, attr) {
        if (scope.$last === true) {
            $timeout(function () {
                scope.$emit('ngRepeatFinished');
            });
        }
    }
}
});

Complete example in angular: http://jsfiddle.net/ADukg/6880/

I got the directive from here: Use AngularJS just for routing purposes

How to make Java honor the DNS Caching Timeout?

To summarize the other answers, in <jre-path>/lib/security/java.security you can set the value of the property networkaddress.cache.ttl to adjust how DNS lookups are cached. Note that this is not a system property but a security property. I was able to set this using:

java.security.Security.setProperty("networkaddress.cache.ttl", "<value>");

This can also be set by the system property -Dsun.net.inetaddr.ttl though this will not override a security property if it is set elsewhere.

I would also like to add that if you are seeing this issue with web services in WebSphere, as I was, setting networkaddress.cache.ttl will not be enough. You need to set the system property disableWSAddressCaching to true. Unlike the time-to-live property, this can be set as a JVM argument or via System.setProperty).

IBM has a pretty detailed post on how WebSphere handles DNS caching here. The relevant piece to the above is:

To disable address caching for Web services, you need to set an additional JVM custom property disableWSAddressCaching to true. Use this property to disable address caching for Web services. If your system typically runs with lots of client threads, and you encounter lock contention on the wsAddrCache cache, you can set this custom property to true, to prevent caching of the Web services data.

JavaScript replace/regex

You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):

  "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")

Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).

Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

You can find information and a little description of the MBDB/MBDX format here:

http://code.google.com/p/iphonebackupbrowser/

This is my application to browse the backup files. I have tried to document the format of the new files that come with iTunes 9.2.

Dependent DLL is not getting copied to the build output folder in Visual Studio

In my case, it was the stupidest thing, caused by a default behavior of TFS/VS that I disagree with.

Since adding the dll as a reference to the main project did not work, I decided to add it as an "Existing Item", with Copy Local = Always. Even then the file was not there.

Turns out that, even though the file is present on the VS Solution and everything compiled both locally and on the server, VS/TFS did not add actually add the file to source control. It was not included on the "Pending Changes" at all. I had to manually go to the Source Control Explorer and explicitly click on the "Add items to folder" icon.

Stupid because I've been developing for 15 years in VS. I've run into this before, I just did not remember and somehow I missed it because everything still compiled because of the file being a regular reference, but the file that was added as Existing Item was not being copied because it did not exist on the source control server.

I hope this saves someone some time, since I lost 2 days of my life to this.

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

The following will do.

string datestring = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

How can I enable or disable the GPS programmatically on Android?

This code works on ROOTED phones if the app is moved to /system/aps, and they have the following permissions in the manifest:

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>

Code

private void turnGpsOn (Context context) {
    beforeEnable = Settings.Secure.getString (context.getContentResolver(),
                                              Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    String newSet = String.format ("%s,%s",
                                   beforeEnable,
                                   LocationManager.GPS_PROVIDER);
    try {
        Settings.Secure.putString (context.getContentResolver(),
                                   Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
                                   newSet); 
    } catch(Exception e) {}
}


private void turnGpsOff (Context context) {
    if (null == beforeEnable) {
        String str = Settings.Secure.getString (context.getContentResolver(),
                                                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (null == str) {
            str = "";
        } else {                
            String[] list = str.split (",");
            str = "";
            int j = 0;
            for (int i = 0; i < list.length; i++) {
                if (!list[i].equals (LocationManager.GPS_PROVIDER)) {
                    if (j > 0) {
                        str += ",";
                    }
                    str += list[i];
                    j++;
                }
            }
            beforeEnable = str;
        }
    }
    try {
        Settings.Secure.putString (context.getContentResolver(),
                                   Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
                                   beforeEnable);
    } catch(Exception e) {}
}

Get data type of field in select statement in ORACLE

If you don't have privileges to create a view in Oracle, a "hack" around it to use MS Access :-(

In MS Access, create a pass through query with your sql (but add where clause to just select 1 record), create a select query from the view (very important), selecting all *, then create a make table from the select query. When this runs it will create a table with one record, all the data types should "match" oracle. i.e. Passthrough --> Select --> MakeTable --> Table

I am sure there are other better ways, but if you have limited tools and privileges this will work.

syntaxerror: unexpected character after line continuation character in python

Replace

f = open(D\\python\\HW\\2_1 - Copy.cp,"r");

by

f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")

  1. File path needs to be a string (constant)
  2. need colon in Windows file path
  3. space after comma for better style
  4. ; after statement is allowed but fugly.

What tutorial are you using?

Open File Dialog, One Filter for Multiple Excel Extensions?

If you want to merge the filters (eg. CSV and Excel files), use this formula:

OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";

Or if you want to see XML or PDF files in one time use this:

of.Filter = @" XML or PDF |*.xml;*.pdf";

ASP.NET MVC 3 Razor - Adding class to EditorFor

While the question was targeted at MVC 3.0, we find the problem persists in MVC 4.0 as well. MVC 5.0 now includes natively an overload for htmlAttributes.

I am forced to use MVC 4.0 at my current place of employment and needed to add a css class for JQuery integration. I solved this problem using a single extension method...

Extension Method:

using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml.Linq;

namespace MyTest.Utilities
{
    public static class MVCHelperExtensionMethods
    {
        public static MvcHtmlString AddHtmlAttributes(this MvcHtmlString input, object htmlAttributes)
        {
            // WE WANT TO INJECT INTO AN EXISTING ELEMENT.  IF THE ATTRIBUTE ALREADY EXISTS, ADD TO IT, OTHERWISE
            // CREATE THE ATTRIBUTE WITH DATA VALUES.

            // USE XML PARSER TO PARSE HTML ELEMENT
            var xdoc = XDocument.Parse(input.ToHtmlString());
            var rootElement = (from e in xdoc.Elements() select e).FirstOrDefault();

            // IF WE CANNOT PARSE THE INPUT USING XDocument THEN RETURN THE ORIGINAL UNMODIFIED.
            if (rootElement == null)
            {
                return input;
            }

            // USE RouteValueDictionary TO PARSE THE NEW HTML ATTRIBUTES
            var routeValueDictionary = new RouteValueDictionary(htmlAttributes);

            foreach (var routeValue in routeValueDictionary)
            {
                var attribute = rootElement.Attribute(routeValue.Key);

                if (attribute == null)
                {
                    attribute = new XAttribute(name: routeValue.Key, value: routeValue.Value);
                    rootElement.Add(attribute);
                }
                else
                {
                    attribute.Value = string.Format("{0} {1}", attribute.Value, routeValue.Value).Trim();
                }
            }

            var elementString = rootElement.ToString();
            var response = new MvcHtmlString(elementString);
            return response;
        }
    }
}

HTML Markup Usage:

@Html.EditorFor(expression: x => x.MyTestProperty).AddHtmlAttributes(new { @class = "form-control" })

(Make sure to include the extension method's namespace in the razor view)

Explanation: The idea is to inject into the existing HTML. I opted to parse the current element using Linq-to-XML using XDocument.Parse(). I pass the htmlAttributes as type object. I utilize MVC RouteValueDictionary to parse the htmlAttributes passed in. I merge the attributes where they already exist, or add a new attribute if it does not yet exist.

In the event the input is not parsable by XDocument.Parse() I abandon all hope and return the original input string.

Now I can use the benefit of the DisplayFor (rendering datatypes such as currency appropriately) but also have the ability to specify css classes (and any other attribute for that matter). Could be helpful for adding attributes such as data-*, or ng-* (Angular).

Sending "User-agent" using Requests library in Python

The user-agent should be specified as a field in the header.

Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent.

If you're using requests v2.13 and newer

The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

If you're using requests v2.12.x and older

Older versions of requests clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

Array versus linked-list

Linked List are more of an overhead to maintain than array, it also requires additional memory storage all these points are agreed. But there are a few things which array cant do. In many cases suppose you want an array of length 10^9 you can't get it because getting one continous memory location has to be there. Linked list could be a saviour here.

Suppose you want to store multiple things with data then they can be easily extended in the linked list.

STL containers usually have linked list implementation behind the scene.

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

MySQL integer field is returned as string in PHP

I like Chad's answer, especially when the query results will be passed on to javascript in a browser. Javascript deals cleanly with numeric like entities as numbers but requires extra work to deal with numeric like entities as strings. i.e. must use parseInt or parseFloat on them.

Building on Chad's solution I use this and it is often exactly what I need and creates structures that can be JSON encoded for easy dealing with in javascript.

while ($row = $result->fetch_assoc()) {
    // convert numeric looking things to numbers for javascript
    foreach ($row as &$val) {
        if (is_numeric($val))
            $val = $val + 0;
    }
}

Adding a numeric string to 0 produces a numeric type in PHP and correctly identifies the type so floating point numbers will not be truncated into integers.

How to get the current date and time

import java.util.Date;   
Date now = new Date();

Note that the Date object is mutable and if you want to do anything sophisticated, use jodatime.

Linux/Unix command to determine if process is running?

The following shell function, being only based on POSIX standard commands and options should work on most (if not any) Unix and linux system. :

isPidRunning() {
  cmd=`
    PATH=\`getconf PATH\` export PATH
    ps -e -o pid= -o comm= |
      awk '$2 ~ "^.*/'"$1"'$" || $2 ~ "^'"$1"'$" {print $1,$2}'
  `
  [ -n "$cmd" ] &&
    printf "%s is running\n%s\n\n" "$1" "$cmd" ||
    printf "%s is not running\n\n" $1
  [ -n "$cmd" ]
}

$ isPidRunning httpd
httpd is running
586 /usr/apache/bin/httpd
588 /usr/apache/bin/httpd

$ isPidRunning ksh
ksh is running
5230 ksh

$ isPidRunning bash
bash is not running

Note that it will choke when passed the dubious "0]" command name and will also fail to identify processes having an embedded space in their names.

Note too that the most upvoted and accepted solution demands non portable ps options and gratuitously uses a shell that is, despite its popularity, not guaranteed to be present on every Unix/Linux machine (bash)

'typeid' versus 'typeof' in C++

Answering the additional question:

my following test code for typeid does not output the correct type name. what's wrong?

There isn't anything wrong. What you see is the string representation of the type name. The standard C++ doesn't force compilers to emit the exact name of the class, it is just up to the implementer(compiler vendor) to decide what is suitable. In short, the names are up to the compiler.


These are two different tools. typeof returns the type of an expression, but it is not standard. In C++0x there is something called decltype which does the same job AFAIK.

decltype(0xdeedbeef) number = 0; // number is of type int!
decltype(someArray[0]) element = someArray[0];

Whereas typeid is used with polymorphic types. For example, lets say that cat derives animal:

animal* a = new cat; // animal has to have at least one virtual function
...
if( typeid(*a) == typeid(cat) )
{
    // the object is of type cat! but the pointer is base pointer.
}

Create a temporary table in a SELECT statement without a separate CREATE TABLE

Engine must be before select:

CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY 
as (select * from table1)

How to display an error message in an ASP.NET Web Application

The errors in ASP.Net are saved on the Server.GetLastError property,

Or i would put a label on the asp.net page for displaying the error.

try
{
    do something
}
catch (YourException ex)
{
    errorLabel.Text = ex.Message;
    errorLabel.Visible = true;
}

How do I get formatted JSON in .NET using C#?

Using System.Text.Json set JsonSerializerOptions.WriteIndented = true:

JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize<Type>(object, options);

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

jQuery: get the file name selected from <input type="file" />

It is just such simple as writing:

$('input[type=file]').val()

Anyway, I suggest using name or ID attribute to select your input. And with event, it should look like this:

$('input[type=file]').change(function(e){
  $in=$(this);
  $in.next().html($in.val());
});

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

I've encountered the same problem in OSX. I've tried to replace the things like
$cfg['Servers'][$i]['usergroups'] to $cfg['Servers'][$i]['pma__usergroups'] ...

It works in safari but still fails in chrome.
But the so called 'work' in safari can get the message that the features which have been modified are not in effect at all.
However, the 'work' means that I can access the dbs listed left.
I think this problem maybe a bug in the new version of XAMPP, since the #1932 problems in google is new and boomed.
You can have a try at an older version of XAMPP instead until the bug is solved.
http://sourceforge.net/projects/xampp/files/XAMPP%20Linux/5.6.12/
Hope it can help you.

What exceptions should be thrown for invalid or unexpected parameters in .NET?

Depending on the actual value and what exception fits best:

If this is not precise enough, just derive your own exception class from ArgumentException.

Yoooder's answer enlightened me. An input is invalid if it is not valid at any time, while an input is unexpected if it is not valid for the current state of the system. So in the later case an InvalidOperationException is a reasonable choice.

Call Python function from JavaScript code

You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).

  1. Install python and create a sample file test.py

    import sys
    # print sys.argv[0] prints test.py
    # print sys.argv[1] prints your_var_1
    
    def hello():
        print "Hi" + " " + sys.argv[1]
    
    if __name__ == "__main__":
        hello()
    
  2. Create a method in your Web API Server

    [HttpGet]
    public string SayHi(string id)
    {
        string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py";          
    
        Process p = new Process();
        p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName + " " + id)
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        p.Start();
    
        return p.StandardOutput.ReadToEnd();                  
    }
    
  3. And now for your JavaScript:

    function processSayingHi() {          
       var your_param = 'abc';
       $.ajax({
           url: '/api/your_controller_name/SayHi/' + your_param,
           type: 'GET',
           success: function (response) {
               console.log(response);
           },
           error: function (error) {
               console.log(error);
           }
        });
    }
    

Remember that your .py file won't run on your user's computer, but instead on the server.

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

How can I create a table with borders in Android?

What I wanted is a table like this

table image with vertical dividers

I added this in my styles.xml :

      <style name="Divider">
        <item name="android:layout_width">1dip</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:background">@color/divider_color</item>
    </style>

    <style name="Divider_invisible">
        <item name="android:layout_width">1dip</item>
        <item name="android:layout_height">match_parent</item>
    </style>

Then in my table layout :

 <TableLayout
            android:id="@+id/table"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:stretchColumns="*" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:background="#92C94A" >

                <TextView
                    android:id="@+id/textView11"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider_invisible" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView12"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/main_wo_colon"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView13"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/side_wo_colon"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView14"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/total"
                    android:textColor="@color/white"
                    android:textSize="16sp" />
            </TableRow>

            <!-- display this button in 3rd column via layout_column(zero based) -->

            <TableRow
                android:id="@+id/tableRow2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#6F9C33" >

                <TextView
                    android:id="@+id/textView21"
                    android:padding="5dp"
                    android:text="@string/servings"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

..........
.......
......

How do I round a double to two decimal places in Java?

Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:

DecimalFormat twoDForm = new DecimalFormat("#.00");

What method in the String class returns only the first N characters?

public static string TruncateLongString(this string str, int maxLength)
{
    if (string.IsNullOrEmpty(str)) return str;

    return str.Substring(0, Math.Min(str.Length, maxLength));
}

What does "ulimit -s unlimited" do?

When you call a function, a new "namespace" is allocated on the stack. That's how functions can have local variables. As functions call functions, which in turn call functions, we keep allocating more and more space on the stack to maintain this deep hierarchy of namespaces.

To curb programs using massive amounts of stack space, a limit is usually put in place via ulimit -s. If we remove that limit via ulimit -s unlimited, our programs will be able to keep gobbling up RAM for their evergrowing stack until eventually the system runs out of memory entirely.

int eat_stack_space(void) { return eat_stack_space(); }
// If we compile this with no optimization and run it, our computer could crash.

Usually, using a ton of stack space is accidental or a symptom of very deep recursion that probably should not be relying so much on the stack. Thus the stack limit.

Impact on performace is minor but does exist. Using the time command, I found that eliminating the stack limit increased performance by a few fractions of a second (at least on 64bit Ubuntu).

Retrieving the last record in each group - MySQL

Hope below Oracle query can help:

WITH Temp_table AS
(
    Select id, name, othercolumns, ROW_NUMBER() over (PARTITION BY name ORDER BY ID 
    desc)as rank from messages
)
Select id, name,othercolumns from Temp_table where rank=1

Convert JsonNode into POJO

String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
    new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);

If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)

mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);

Is there a way to list all resources in AWS

Yes.

I had the same issue, trying to figure out what exactly is going on in my AWS account.

Eventually, I ended up writing AWSRetriver, a desktop tool to list AWS resources on all regions.

It is a simple and straight-forward tool that lists everything... (hopefully) AWS Resources

Where is the itoa function in Linux?

As Matt J wrote, there is itoa, but it's not standard. Your code will be more portable if you use snprintf.

How to restart Activity in Android

Well this is not listed but a combo of some that is already posted:

if (Build.VERSION.SDK_INT >= 11) {
    recreate();   
} else {
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

How to parse JSON in Scala using standard Scala classes?

val jsonString =
  """
    |{
    | "languages": [{
    |     "name": "English",
    |     "is_active": true,
    |     "completeness": 2.5
    | }, {
    |     "name": "Latin",
    |     "is_active": false,
    |     "completeness": 0.9
    | }]
    |}
  """.stripMargin

val result = JSON.parseFull(jsonString).map {
  case json: Map[String, List[Map[String, Any]]] =>
    json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get

println(result)

assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )

Refresh a page using JavaScript or HTML

Here are 535 ways to reload a page using javascript, very cool:

Here are the first 20:

location = location
location = location.href
location = window.location
location = self.location
location = window.location.href
location = self.location.href
location = location['href']
location = window['location']
location = window['location'].href
location = window['location']['href']
location = window.location['href']
location = self['location']
location = self['location'].href
location = self['location']['href']
location = self.location['href']
location.assign(location)
location.replace(location)
window.location.assign(location)
window.location.replace(location)
self.location.assign(location)

and the last 10:

self['location']['replace'](self.location['href'])
location.reload()
location['reload']()
window.location.reload()
window['location'].reload()
window.location['reload']()
window['location']['reload']()
self.location.reload()
self['location'].reload()
self.location['reload']()
self['location']['reload']()

Original Article

How to retrieve GET parameters from JavaScript

My solution expands on @tak3r's.

It returns an empty object when there are no query parameters and supports the array notation ?a=1&a=2&a=3:

function getQueryParams () {
  function identity (e) { return e; }
  function toKeyValue (params, param) {
    var keyValue = param.split('=');
    var key = keyValue[0], value = keyValue[1];

    params[key] = params[key]?[value].concat(params[key]):value;
    return params;
  }
  return decodeURIComponent(window.location.search).
    replace(/^\?/, '').split('&').
    filter(identity).
    reduce(toKeyValue, {});
}

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Things you can add to declarations: [] in modules

  • Pipe
  • Directive
  • Component

Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.

How do I iterate through each element in an n-dimensional matrix in MATLAB?

The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,

A = magic(3)
A =
     8     1     6
     3     5     7
     4     9     2

A(2,3)
ans =
     7

A(8)
ans =
     7

We can see the order the elements are stored in memory by unrolling the array into a vector.

A(:)
ans =
     8
     3
     4
     1
     5
     9
     6
     7
     2

As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.

find(A>6)
ans =
     1
     6
     8

The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:

B = zeros(size(A));
for i = 1:numel(A)
  B(i) = A(i).^2;
end

B
B =
    64     1    36
     9    25    49
    16    81     4

There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.

The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)

How to use RANK() in SQL Server

You have to use DENSE_RANK rather than RANK. The only difference is that it doesn't leave gaps. You also shouldn't partition by contender_num, otherwise you're ranking each contender in a separate group, so each is 1st-ranked in their segregated groups!

SELECT contendernum,totals, DENSE_RANK() OVER (ORDER BY totals desc) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
 GROUP BY ContenderNum
) AS a
order by contendernum

A hint for using StackOverflow, please post DDL and sample data so people can help you using less of their own time!

create table Cat1GroupImpersonation (
contendernum int,
criteria1 int,
criteria2 int,
criteria3 int,
criteria4 int);

insert Cat1GroupImpersonation select
1,196,0,0,0 union all select
2,181,0,0,0 union all select
3,192,0,0,0 union all select
4,181,0,0,0 union all select
5,179,0,0,0;

React Native: Possible unhandled promise rejection

You should add the catch() to the end of the Api call. When your code hits the catch() it doesn't return anything, so data is undefined when you try to use setState() on it. The error message actually tells you this too :)

Dynamically adding HTML form field using jQuery

This will insert a new element after the input field with id "password".

$(document).ready(function(){
  var newInput = $("<input name='new_field' type='text'>");
  $('input#password').after(newInput);
});

Not sure if this answers your question.

Intent from Fragment to Activity

You need to use getActivity() method from fragment for Intents.

Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);

Recommended date format for REST GET API

Every datetime field in input/output needs to be in UNIX/epoch format. This avoids the confusion between developers across different sides of the API.

Pros:

  • Epoch format does not have a timezone.
  • Epoch has a single format (Unix time is a single signed number).
  • Epoch time is not effected by daylight saving.
  • Most of the Backend frameworks and all native ios/android APIs support epoch conversion.
  • Local time conversion part can be done entirely in application side depends on the timezone setting of user's device/browser.

Cons:

  • Extra processing for converting to UTC for storing in UTC format in the database.
  • Readability of input/output.
  • Readability of GET URLs.

Notes:

  • Timezones are a presentation-layer problem! Most of your code shouldn't be dealing with timezones or local time, it should be passing Unix time around.
  • If you want to store a humanly-readable time (e.g. logs), consider storing it along with Unix time, not instead of Unix time.

How to add a border to a widget in Flutter?

Best way is using BoxDecoration()

Advantage

  • You can set border of widget
  • You can set border Color or Width
  • You can set Rounded corner of border
  • You can add Shadow of widget

Disadvantage

  • BoxDecoration only use with Container widget so you want to wrap your widget in Container()

Example

    Container(
      margin: EdgeInsets.all(10),
      padding: EdgeInsets.all(10),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.orange,
        border: Border.all(
            color: Colors.pink[800],// set border color
            width: 3.0),   // set border width
        borderRadius: BorderRadius.all(
            Radius.circular(10.0)), // set rounded corner radius
        boxShadow: [BoxShadow(blurRadius: 10,color: Colors.black,offset: Offset(1,3))]// make rounded corner of border
      ),
      child: Text("My demo styling"),
    )

enter image description here

How to put img inline with text

Please make use of the code below to display images inline:

<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>

What is mod_php?

Your server needs to have the php modules installed so it can parse php code.

If you are on ubuntu you can do this easily with

sudo apt-get install apache2

sudo apt-get install php5

sudo apt-get install libapache2-mod-php5

sudo /etc/init.d/apache2 restart

Otherwise you may compile apache with php: http://dan.drydog.com/apache2php.html

Specifying your server OS will help others to answer more specifically.

Commenting multiple lines in DOS batch file

@jeb

And after using this, the stderr seems to be inaccessible

No, try this:

@echo off 2>Nul 3>Nul 4>Nul

   ben ali  
   mubarak 2>&1
   gadeffi
   ..next ?

   echo hello Tunisia

  pause

But why it works?

sorry, i answer the question in frensh:

( la redirection par 3> est spécial car elle persiste, on va l'utiliser pour capturer le flux des erreurs 2> est on va le transformer en un flux persistant à l'ade de 3> ceci va nous permettre d'avoir une gestion des erreur pour tout notre environement de script..par la suite si on veux recuperer le flux 'stderr' il faut faire une autre redirection du handle 2> au handle 1> qui n'est autre que la console.. )

How to retrieve data from a SQL Server database in C#?

To retrieve data from database:

private SqlConnection Conn;
 private void CreateConnection()
 {
    string ConnStr =
    ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    Conn = new SqlConnection(ConnStr);
 }
 public DataTable getData()
 {
 CreateConnection();
    string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
    DataTable dt = new DataTable();
    try
    {
        Conn.Open();
        sda.Fill(dt);
    }
    catch (SqlException se)
    {
        DBErLog.DbServLog(se, se.ToString());
    }
    finally
    {
        Conn.Close();
    }
    return dt;
}

How to embed a SWF file in an HTML page?

Thi works on IE, Edge, Firefox, Safari and Chrome.

<object type="application/x-shockwave-flash" data="movie.swf" width="720" height="480">
  <param name="movie" value="movie.swf" />
  <param name="quality" value="high" />
  <param name="bgcolor" value="#000000" />
  <param name="play" value="true" />
  <param name="loop" value="true" />
  <param name="wmode" value="window" />
  <param name="scale" value="showall" />
  <param name="menu" value="true" />
  <param name="devicefont" value="false" />
  <param name="salign" value="" />
  <param name="allowScriptAccess" value="sameDomain" />
  <a href="http://www.adobe.com/go/getflash">
    <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
  </a>
</object>

Add target="_blank" in CSS

As c69 mentioned there is no way to do it with pure CSS.

but you can use HTML instead:

use

<head>
    <base target="_blank">
</head>

in your HTML <head> tag for making all of page links which not include target attribute to be opened in a new blank window by default. otherwise you can set target attribute for each link like this:

    <a href="/yourlink.html" target="_blank">test-link</a>

and it will override

<head>
    <base target="_blank">
</head>

tag if it was defined previously.

How can I format the output of a bash command in neat columns

Try

xargs -n2  printf "%-20s%s\n"

or even

xargs printf "%-20s%s\n"

if input is not very large.

SQL Server: Make all UPPER case to Proper Case/Title Case

Just learned about InitCap().

Here is some sample code:

SELECT ID
      ,InitCap(LastName ||', '|| FirstName ||' '|| Nvl(MiddleName,'')) AS RecipientName
FROM SomeTable

Regular expression to match exact number of characters?

Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:

^([A-Z]{3})$

The {3} indicates that the [A-Z] must appear exactly 3 times.

Java Date cut off time information

With Joda-Time since version 2.0 you can use LocalDate.toDate().

Simply

// someDatetime is whatever java.util.Date you have.
Date someDay = new LocalDate(someDatetime).toDate();

Checkout Jenkins Pipeline Git SCM with credentials?

You can use the following in a pipeline:

git branch: 'master',
    credentialsId: '12345-1234-4696-af25-123455',
    url: 'ssh://[email protected]:company/repo.git'

If you're using the ssh url then your credentials must be username + private key. If you're using the https clone url instead of the ssh one, then your credentials should be username + password.

jQuery's .on() method combined with the submit event

The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:

$('form').on('submit',doFormStuff);

createNewForm();

// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);

Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:

function bindItems(){
    $('form').off('submit').on('submit',doFormStuff); 
    $('button').off('click').on('click',doButtonStuff);
}   

So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.

createNewButton();
bindItems();

I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.

useState set method not reflecting change immediately

Much like setState in Class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately.

Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.

Even if you add a setTimeout the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout will still use the value from its previous closure and not the updated one.

setMovies(result);
console.log(movies) // movies here will not be updated

If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn't have a callback pattern

useEffect(() => {
    // action on update of movies
}, [movies]);

As far as the syntax to update state is concerned, setMovies(result) will replace the previous movies value in the state with those available from the async request.

However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like

setMovies(prevMovies => ([...prevMovies, ...result]));

Make content horizontally scroll inside a div

Same as what clairesuzy answered, except you can get a similar result by adding display: flex instead of white-space: nowrap. Using display: flex will collapse the img "margins", in case that behavior is preferred.

Example JavaScript code to parse CSV data

Here's my simple vanilla JavaScript code:

let a = 'one,two,"three, but with a comma",four,"five, with ""quotes"" in it.."'
console.log(splitQuotes(a))

function splitQuotes(line) {
  if(line.indexOf('"') < 0) 
    return line.split(',')

  let result = [], cell = '', quote = false;
  for(let i = 0; i < line.length; i++) {
    char = line[i]
    if(char == '"' && line[i+1] == '"') {
      cell += char
      i++
    } else if(char == '"') {
      quote = !quote;
    } else if(!quote && char == ',') {
      result.push(cell)
      cell = ''
    } else {
      cell += char
    }
    if ( i == line.length-1 && cell) {
      result.push(cell)
    }
  }
  return result
}

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

SQL Server loop - how do I loop through a set of records

By using cursor you can easily iterate through records individually and print records separately or as a single message including all the records.

DECLARE @CustomerID as INT;
declare @msg varchar(max)
DECLARE @BusinessCursor as CURSOR;

SET @BusinessCursor = CURSOR FOR
SELECT CustomerID FROM Customer WHERE CustomerID IN ('3908745','3911122','3911128','3911421')

OPEN @BusinessCursor;
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
    WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @msg = '{
              "CustomerID": "'+CONVERT(varchar(10), @CustomerID)+'",
              "Customer": {
                "LastName": "LastName-'+CONVERT(varchar(10), @CustomerID) +'",
                "FirstName": "FirstName-'+CONVERT(varchar(10), @CustomerID)+'",    
              }
            }|'
        print @msg
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
END

Add swipe to delete UITableViewCell

Swift 4 -- @available(iOS 11.0, *)

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let edit = UIContextualAction(style: .normal, title: "") { (action, view, nil) in
        let refreshAlert = UIAlertController(title: "Deletion", message: "Are you sure you want to remove this item from cart? ", preferredStyle: .alert)

        refreshAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in

        }))

        refreshAlert.addAction(UIAlertAction(title: "No", style: .default, handler: { (action: UIAlertAction!) in
            refreshAlert .dismiss(animated: true, completion: nil)
        }))

        self.present(refreshAlert, animated: true, completion: nil)
    }
    edit.backgroundColor = #colorLiteral(red: 0.3215686275, green: 0.5960784314, blue: 0.2470588235, alpha: 1)
    edit.image = #imageLiteral(resourceName: "storyDelete")
    let config = UISwipeActionsConfiguration(actions: [edit])
    config.performsFirstActionWithFullSwipe = false
    return config
}

Form Submit Execute JavaScript Best Practice?

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.

For example:

<script>
function doSomething() {
    alert('Form submitted!');
    return false;
}
</script>

<form onsubmit="return doSomething();" class="my-form">
    <input type="submit" value="Submit">
</form>

This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

<script>
$('.my-form').on('submit', function () {
    alert('Form submitted!');
    return false;
});
</script>

<form class="my-form">
    <input type="submit" value="Submit">
</form>

how can get index & count in vuejs

you can just add 1

<li v-for="(catalog, itemObjKey) in catalogs">this index : {{itemObjKey + 1}}</li>

to get the length of an array/objects

{{ catalogs.length }}

How to create a hash or dictionary object in JavaScript

Use the in operator: e.g. "key1" in a.

How do I make a C++ macro behave like a function?

As others have mentioned, you should avoid macros whenever possible. They are dangerous in the presence of side effects if the macro arguments are evaluated more than once. If you know the type of the arguments (or can use C++0x auto feature), you could use temporaries to enforce single evaluation.

Another problem: the order in which multiple evaluations happen may not be what you expect!

Consider this code:

#include <iostream>
using namespace std;

int foo( int & i ) { return i *= 10; }
int bar( int & i ) { return i *= 100; }

#define BADMACRO( X, Y ) do { \
    cout << "X=" << (X) << ", Y=" << (Y) << ", X+Y=" << ((X)+(Y)) << endl; \
    } while (0)

#define MACRO( X, Y ) do { \
    int x = X; int y = Y; \
    cout << "X=" << x << ", Y=" << y << ", X+Y=" << ( x + y ) << endl; \
    } while (0)

int main() {
    int a = 1; int b = 1;
    BADMACRO( foo(a), bar(b) );
    a = 1; b = 1;
    MACRO( foo(a), bar(b) );
    return 0;
}

And it's output as compiled and run on my machine:

X=100, Y=10000, X+Y=110
X=10, Y=100, X+Y=110

Python: "TypeError: __str__ returned non-string" but still prints to output?

Just Try this:

def __str__(self):
    return f'Memo={self.memo}, Tag={self.tags}'

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

  1. you need to create and id for the buttons you need to refference: btn1.setId(1);
  2. you can use the params variable to add parameters to your layout, i think the method is addRule(), check out the android java docs for this LayoutParams object.

How to use sys.exit() in Python

I think you can use

sys.exit(0)

You may check it here in the python 2.7 doc:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.

How can I capitalize the first letter of each word in a string?

As Mark pointed out, you should use .title():

"MyAwesomeString".title()

However, if would like to make the first letter uppercase inside a Django template, you could use this:

{{ "MyAwesomeString"|title }}

Or using a variable:

{{ myvar|title }}

How do I see which checkbox is checked?

If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.

if (isset($_POST['mycheckbox'])) {
    echo "checked!";
}

Remove a symlink to a directory

rm should remove the symbolic link.

skrall@skrall-desktop:~$ mkdir bar
skrall@skrall-desktop:~$ ln -s bar foo
skrall@skrall-desktop:~$ ls -l foo
lrwxrwxrwx 1 skrall skrall 3 2008-10-16 16:22 foo -> bar
skrall@skrall-desktop:~$ rm foo
skrall@skrall-desktop:~$ ls -l foo
ls: cannot access foo: No such file or directory
skrall@skrall-desktop:~$ ls -l bar
total 0
skrall@skrall-desktop:~$ 

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

How to get the first 2 letters of a string in Python?

In general, you can the characters of a string from i until j with string[i:j]. string[:2] is shorthand for string[0:2]. This works for arrays as well.

Learn about python's slice notation at the official tutorial

Convert number to month name in PHP

This is how I did it

// sets Asia/Calcutta time zone
date_default_timezone_set("Asia/Calcutta");

//fetches current date and time
$date = date("Y-m-d H:i:s");

$dateArray = date_parse_from_format('Y/m/d', $date);
$month = DateTime::createFromFormat('!m', $dateArray['month'])->format('F');
$dateString = $dateArray['day'] . " " . $month  . " " . $dateArray['year'];

echo $dateString;

returns 30 June 2019

Video format or MIME type is not supported

For Ubuntu 14.04

Just removed the package Oxideqt-dodecs then install flash or ubuntu restricted extras

and you are good to go!!

Issue with background color in JavaFX 8

Both these work for me. Maybe post a complete example?

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class PaneBackgroundTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();
        VBox vbox = new VBox();
        root.setCenter(vbox);

        ToggleButton toggle = new ToggleButton("Toggle color");
        HBox controls = new HBox(5, toggle);
        controls.setAlignment(Pos.CENTER);
        root.setBottom(controls);

//        vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
//                .then("-fx-background-color: cornflowerblue;")
//                .otherwise("-fx-background-color: white;"));

        vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
                .then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
                .otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

How do you enable auto-complete functionality in Visual Studio C++ express edition?

It's enabled by default. Probably you just tried on an expression that failed to autocomplete.

In case you deactivated it somehow... you can enable it in the Visual Studio settings. Just browse to the Editor settings, then to the subgroup C/C++ and activate it again... should read something like "List members automatically" or "Auto list members" (sorry, I have the german Visual Studio).

Upon typing something like std::cout. a dropwdownlist with possible completitions should pop up.

How can I strip HTML tags from a string in ASP.NET?

If it is just stripping all HTML tags from a string, this works reliably with regex as well. Replace:

<[^>]*(>|$)

with the empty string, globally. Don't forget to normalize the string afterwards, replacing:

[\s\r\n]+

with a single space, and trimming the result. Optionally replace any HTML character entities back to the actual characters.

Note:

  1. There is a limitation: HTML and XML allow > in attribute values. This solution will return broken markup when encountering such values.
  2. The solution is technically safe, as in: The result will never contain anything that could be used to do cross site scripting or to break a page layout. It is just not very clean.
  3. As with all things HTML and regex:
    Use a proper parser if you must get it right under all circumstances.

How to set the default value of an attribute on a Laravel model

You should set default values in migrations:

$table->tinyInteger('role')->default(1);

how to remove pagination in datatable

if you want to remove pagination and but want ordering of dataTable then add this script at the end of your page!

_x000D_
_x000D_
<script>_x000D_
$(document).ready(function() {        _x000D_
    $('#table_id').DataTable({_x000D_
        "paging":   false,_x000D_
       "info":     false_x000D_
    } );_x000D_
      _x000D_
  } );_x000D_
</script>
_x000D_
_x000D_
_x000D_

append to url and refresh page

Please check the below code :

/*Get current URL*/    
var _url = location.href; 
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'&param='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;

Convert a dta file to csv without Stata software

SPSS can also read .dta files and export them to .csv, but that costs money. PSPP, an open source version of SPSS, which is rough, might also be able to read/export .dta files.

How to simulate browsing from various locations?

The only thing that springs to mind for this is to use a proxy server based in Europe. Either have your colleague set one up [if possible] or find a free proxy. A quick Google search came up with http://www.anonymousinet.com/ as the top result.

Convert DateTime to TimeSpan

TimeSpan.FromTicks(DateTime.Now.Ticks)

How to find all the subclasses of a class given its name?

Here is a simple but efficient version of code:

def get_all_subclasses(cls):
    subclass_list = []

    def recurse(klass):
        for subclass in klass.__subclasses__():
            subclass_list.append(subclass)
            recurse(subclass)

    recurse(cls)

    return set(subclass_list)

Its time complexity is O(n) where n is the number of all subclasses if there's no multiple inheritance. It's more efficient than the functions that recursively create lists or yield classes with generators, whose complexity could be (1) O(nlogn) when the class hierarchy is a balanced tree or (2) O(n^2) when the class hierarchy is a biased tree.

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

Specifying Font and Size in HTML table

Enclose your code with the html and body tags. Size attribute does not correspond to font-size and it looks like its domain does not go beyond value 7. Furthermore font tag is not supported in HTML5. Consider this code for your case

<!DOCTYPE html>
<html>
<body>

<font size="2" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td>
    </tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td><td>master.mdf</td>
        <td>test_key_16</td><td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td>
    </tr>
</table>
</font>
<font size="5" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td></tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td>
        <td>master.mdf</td>
        <td>test_key_16</td>
        <td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td></tr>
</table></font>
</body>
</html>

jQuery Remove string from string

If you just want to remove "username1" you can use a simple replace.

name.replace("username1,", "")

or you could use split like you mentioned.

var name = "username1, username2 and username3 like this post.".split(",")[1];      
$("h1").text(name);

jsfiddle example

Angular 2 Checkbox Two Way Data Binding

Unfortunately solution provided by @hakani is not two-way binding. It just handles One-way changing model from UI/FrontEnd part.

Instead the simple:

<input [(ngModel)]="checkboxFlag" type="checkbox"/>

will do two-way binding for checkbox.

Afterwards, when Model checkboxFlag is changed from Backend or UI part - voila, checkboxFlag stores actual checkbox state.

To be sure I've prepared Plunker code to present the result : https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk

Just to complete this answer you should include the import { FormsModule } from '@angular/forms' into app.module.ts and add to imports array i.e

import { FormsModule } from '@angular/forms';

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

Java Replace Line In Text File

At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:

public static void replaceSelected(String replaceWith, String type) {
    try {
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

        // logic to replace lines in the string (could use regex here to be generic)
        if (type.equals("0")) {
            inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); 
        } else if (type.equals("1")) {
            inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
        }

        // display the new file for debugging
        System.out.println("----------------------------------\n" + inputStr);

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputStr.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

Then call it:

public static void main(String[] args) {
    replaceSelected("Do the dishes", "1");   
}

Original Text File Content:

Do the dishes0
Feed the dog0
Cleaned my room1

Output:

Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1

New text file content:

Do the dishes1
Feed the dog0
Cleaned my room1


And as a note, if the text file was:

Do the dishes1
Feed the dog0
Cleaned my room1

and you used the method replaceSelected("Do the dishes", "1");, it would just not change the file.


Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).

// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
    try {
        // input the (modified) file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            line = ... // replace the line here
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputBuffer.toString().getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

Clicking HTML 5 Video element to play, pause video, breaks play button

I had this same problem and solved it by adding an event handler for the play action in addition to the click action. I hide the controls while playing to avoid the pause button issue.

    var v = document.getElementById('videoID');
    v.addEventListener(
       'play', 
          function() { 
             v.play();
          }, 
        false);

    v.onclick = function() {
      if (v.paused) {
        v.play();
        v.controls=null;
      } else {
        v.pause();
        v.controls="controls";
      }
    };

Seeking still acts funny though, but at least the confusion with the play control is gone. Hope this helps.

Anyone have a solution to that?

Bundler: Command not found

My solution was to make sure I selected a version of Ruby for that repo.

Example: chruby 2.2.2 or rvm use 2.2.2

? bundle install
zsh: command not found: bundle

? ruby -v
ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]

### Notice the system Ruby version isn't included in chruby

? chruby
  ruby-1.9.3-p551
  ruby-2.1.2
  ruby-2.2.1

### Select a version via your version manager

? chruby 1.9.3

### Ensure your version manager properly selects a version (*)

? chruby
 * ruby-1.9.3-p551
   ruby-2.1.2
   ruby-2.2.1

? bundle install
Fetching gem metadata from https://rubygems.org/.........

What linux shell command returns a part of a string?

In bash you can try this:

stringZ=abcABC123ABCabc
#       0123456789.....
#       0-based indexing.

echo ${stringZ:0:2} # prints ab

More samples in The Linux Documentation Project

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

Converting NSString to NSDate (and back again)

String To Date

var dateFormatter = DateFormatter()
dateFormatter.format = "dd/MM/yyyy"

var dateFromString: Date? = dateFormatter.date(from: dateString) //pass string here

Date To String

 var dateFormatter = DateFormatter()
 dateFormatter.dateFormat = "dd-MM-yyyy"
 let newDate = dateFormatter.string(from: date) //pass Date here

How to list physical disks?

GetLogicalDrives() enumerates all mounted disk partitions, not physical drives.

You can enumerate the drive letters with (or without) GetLogicalDrives, then call QueryDosDevice() to find out which physical drive the letter is mapped to.

Alternatively, you can decode the information in the registry at HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices. The binary data encodings there are not obvious, however. If you have a copy of Russinovich and Solomon's book Microsoft Windows Internals, this registry hive is discussed in Chapter 10.

How do I parse JSON in Android?

I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:

try{
    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient();
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet("http://example.json");

    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json);

} catch(Exception e){
    // In your production code handle any errors and catch the individual exceptions
    e.printStackTrace();
}

Once you have your JSONObject refer to the SDK for details on how to extract the data you require.

How to launch an EXE from Web page (asp.net)

if the applications are C#, you can use ClickOnce deployment, which is a good option if you can't guarentee the user will have the app, however you'll have to re-build the apps with deployment options and grab some boilerplate code from each project.

You can also use Javascript.

Or you can register an application to handle a new web protocol you can define. This could also be an "app selection" protocol, so each time an app is clicked it would link to a page on your new protocol, all handling of this protocol is then passed to your "selection app" which uses arguments to find and launch an app on the clients PC.

HTH

How to split a string in Ruby and get all items except the first one?

ex.split(',', 2).last

The 2 at the end says: split into 2 pieces, not more.

normally split will cut the value into as many pieces as it can, using a second value you can limit how many pieces you will get. Using ex.split(',', 2) will give you:

["test1", "test2, test3, test4, test5"]

as an array, instead of:

["test1", "test2", "test3", "test4", "test5"]

Accessing elements of Python dictionary by index

Few people appear, despite the many answers to this question, to have pointed out that dictionaries are un-ordered mappings, and so (until the blessing of insertion order with Python 3.7) the idea of the "first" entry in a dictionary literally made no sense. And even an OrderedDict can only be accessed by numerical index using such uglinesses as mydict[mydict.keys()[0]] (Python 2 only, since in Python 3 keys() is a non-subscriptable iterator.)

From 3.7 onwards and in practice in 3,6 as well - the new behaviour was introduced then, but not included as part of the language specification until 3.7 - iteration over the keys, values or items of a dict (and, I believe, a set also) will yield the least-recently inserted objects first. There is still no simple way to access them by numerical index of insertion.

As to the question of selecting and "formatting" items, if you know the key you want to retrieve in the dictionary you would normally use the key as a subscript to retrieve it (my_var = mydict['Apple']).

If you really do want to be able to index the items by entry number (ignoring the fact that a particular entry's number will change as insertions are made) then the appropriate structure would probably be a list of two-element tuples. Instead of

mydict = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} }

you might use:

mylist = [
    ('Apple', {'American':'16', 'Mexican':10, 'Chinese':5}),
    ('Grapes', {'Arabian': '25', 'Indian': '20'}
]

Under this regime the first entry is mylist[0] in classic list-endexed form, and its value is ('Apple', {'American':'16', 'Mexican':10, 'Chinese':5}). You could iterate over the whole list as follows:

for (key, value) in mylist:  # unpacks to avoid tuple indexing
    if key == 'Apple':
        if 'American' in value:
            print(value['American'])

but if you know you are looking for the key "Apple", why wouldn't you just use a dict instead?

You could introduce an additional level of indirection by cacheing the list of keys, but the complexities of keeping two data structures in synchronisation would inevitably add to the complexity of your code.

How do you Make A Repeat-Until Loop in C++?

Just use:

do
{
  //enter code here
} while ( !condition );

So what this does is, it moves your 'check for condition' part to the end, since the while is at the end. So it only checks the condition after running the code, just like how you want it

Find size of object instance in bytes in c#

For unmanaged types aka value types, structs:

        Marshal.SizeOf(object);

For managed objects the closer i got is an approximation.

        long start_mem = GC.GetTotalMemory(true);

        aclass[] array = new aclass[1000000];
        for (int n = 0; n < 1000000; n++)
            array[n] = new aclass();

        double used_mem_median = (GC.GetTotalMemory(false) - start_mem)/1000000D;

Do not use serialization.A binary formatter adds headers, so you can change your class and load an old serialized file into the modified class.

Also it won't tell you the real size in memory nor will take into account memory alignment.

[Edit] By using BiteConverter.GetBytes(prop-value) recursivelly on every property of your class you would get the contents in bytes, that doesn't count the weight of the class or references but is much closer to reality. I would recommend to use a byte array for data and an unmanaged proxy class to access values using pointer casting if size matters, note that would be non-aligned memory so on old computers is gonna be slow but HUGE datasets on MODERN RAM is gonna be considerably faster, as minimizing the size to read from RAM is gonna be a bigger impact than unaligned.

What’s the best way to get an HTTP response code from a URL?

You should use urllib2, like this:

import urllib2
for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
    try:
        connection = urllib2.urlopen(url)
        print connection.getcode()
        connection.close()
    except urllib2.HTTPError, e:
        print e.getcode()

# Prints:
# 200 [from the try block]
# 404 [from the except block]

Update all objects in a collection using LINQ

collection.ToList().ForEach(c => c.PropertyToSet = value);

jQuery - Detect value change on hidden input field

Building off of Viktar's answer, here's an implementation you can call once on a given hidden input element to ensure that subsequent change events get fired whenever the value of the input element changes:

/**
 * Modifies the provided hidden input so value changes to trigger events.
 *
 * After this method is called, any changes to the 'value' property of the
 * specified input will trigger a 'change' event, just like would happen
 * if the input was a text field.
 *
 * As explained in the following SO post, hidden inputs don't normally
 * trigger on-change events because the 'blur' event is responsible for
 * triggering a change event, and hidden inputs aren't focusable by virtue
 * of being hidden elements:
 * https://stackoverflow.com/a/17695525/4342230
 *
 * @param {HTMLInputElement} inputElement
 *   The DOM element for the hidden input element.
 */
function setupHiddenInputChangeListener(inputElement) {
  const propertyName = 'value';

  const {get: originalGetter, set: originalSetter} =
    findPropertyDescriptor(inputElement, propertyName);

  // We wrap this in a function factory to bind the getter and setter values
  // so later callbacks refer to the correct object, in case we use this
  // method on more than one hidden input element.
  const newPropertyDescriptor = ((_originalGetter, _originalSetter) => {
    return {
      set: function(value) {
        const currentValue = originalGetter.call(inputElement);

        // Delegate the call to the original property setter
        _originalSetter.call(inputElement, value);

        // Only fire change if the value actually changed.
        if (currentValue !== value) {
          inputElement.dispatchEvent(new Event('change'));
        }
      },

      get: function() {
        // Delegate the call to the original property getter
        return _originalGetter.call(inputElement);
      }
    }
  })(originalGetter, originalSetter);

  Object.defineProperty(inputElement, propertyName, newPropertyDescriptor);
};

/**
 * Search the inheritance tree of an object for a property descriptor.
 *
 * The property descriptor defined nearest in the inheritance hierarchy to
 * the class of the given object is returned first.
 *
 * Credit for this approach:
 * https://stackoverflow.com/a/38802602/4342230
 *
 * @param {Object} object
 * @param {String} propertyName
 *   The name of the property for which a descriptor is desired.
 *
 * @returns {PropertyDescriptor, null}
 */
function findPropertyDescriptor(object, propertyName) {
  if (object === null) {
    return null;
  }

  if (object.hasOwnProperty(propertyName)) {
    return Object.getOwnPropertyDescriptor(object, propertyName);
  }
  else {
    const parentClass = Object.getPrototypeOf(object);

    return findPropertyDescriptor(parentClass, propertyName);
  }
}

Call this on document ready like so:

$(document).ready(function() {
  setupHiddenInputChangeListener($('myinput')[0]);
});

How to get the input from the Tkinter Text Widget?

In order to obtain the string in a Text widget one can simply use get method defined for Text which accepts 1 to 2 arguments as start and end positions of characters, text_widget_object.get(start, end=None). If only start is passed and end isn't passed it returns only the single character positioned at start, if end is passed as well, it returns all characters in between positions start and end as string.

There are also special strings, that are variables to the underlying Tk. One of them would be "end" or tk.END which represents the variable position of the very last char in the Text widget. An example would be to returning all text in the widget, with text_widget_object.get('1.0', 'end') or text_widget_object.get('1.0', 'end-1c') if you don't want the last newline character.

Demo

See below demonstration that selects the characters in between the given positions with sliders:

try:
    import tkinter as tk
except:
    import Tkinter as tk


class Demo(tk.LabelFrame):
    """
    A LabeFrame that in order to demonstrate the string returned by the
    get method of Text widget, selects the characters in between the
    given arguments that are set with Scales.
    """

    def __init__(self, master, *args, **kwargs):
        tk.LabelFrame.__init__(self, master, *args, **kwargs)
        self.start_arg = ''
        self.end_arg = None
        self.position_frames = dict()
        self._create_widgets()
        self._layout()
        self.update()


    def _create_widgets(self):
        self._is_two_args = tk.Checkbutton(self,
                                    text="Use 2 positional arguments...")
        self.position_frames['start'] = PositionFrame(self,
                                    text="start='{}.{}'.format(line, column)")
        self.position_frames['end'] = PositionFrame(   self,
                                    text="end='{}.{}'.format(line, column)")
        self.text = TextWithStats(self, wrap='none')
        self._widget_configs()


    def _widget_configs(self):
        self.text.update_callback = self.update
        self._is_two_args.var = tk.BooleanVar(self, value=False)
        self._is_two_args.config(variable=self._is_two_args.var,
                                    onvalue=True, offvalue=False)
        self._is_two_args['command'] = self._is_two_args_handle
        for _key in self.position_frames:
            self.position_frames[_key].line.slider['command'] = self.update
            self.position_frames[_key].column.slider['command'] = self.update


    def _layout(self):
        self._is_two_args.grid(sticky='nsw', row=0, column=1)
        self.position_frames['start'].grid(sticky='nsew', row=1, column=0)
        #self.position_frames['end'].grid(sticky='nsew', row=1, column=1)
        self.text.grid(sticky='nsew', row=2, column=0,
                                                    rowspan=2, columnspan=2)
        _grid_size = self.grid_size()
        for _col in range(_grid_size[0]):
            self.grid_columnconfigure(_col, weight=1)
        for _row in range(_grid_size[1] - 1):
            self.grid_rowconfigure(_row + 1, weight=1)


    def _is_two_args_handle(self):
        self.update_arguments()
        if self._is_two_args.var.get():
            self.position_frames['end'].grid(sticky='nsew', row=1, column=1)
        else:
            self.position_frames['end'].grid_remove()


    def update(self, event=None):
        """
        Updates slider limits, argument values, labels representing the
        get method call.
        """

        self.update_sliders()
        self.update_arguments()


    def update_sliders(self):
        """
        Updates slider limits based on what's written in the text and
        which line is selected.
        """

        self._update_line_sliders()
        self._update_column_sliders()


    def _update_line_sliders(self):
        if self.text.lines_length:
            for _key in self.position_frames:
                self.position_frames[_key].line.slider['state'] = 'normal'
                self.position_frames[_key].line.slider['from_'] = 1
                _no_of_lines = self.text.line_count
                self.position_frames[_key].line.slider['to'] = _no_of_lines
        else:
            for _key in self.position_frames:
                self.position_frames[_key].line.slider['state'] = 'disabled'


    def _update_column_sliders(self):
        if self.text.lines_length:
            for _key in self.position_frames:
                self.position_frames[_key].column.slider['state'] = 'normal'
                self.position_frames[_key].column.slider['from_'] = 0
                _line_no = int(self.position_frames[_key].line.slider.get())-1
                _max_line_len = self.text.lines_length[_line_no]
                self.position_frames[_key].column.slider['to'] = _max_line_len
        else:
            for _key in self.position_frames:
                self.position_frames[_key].column.slider['state'] = 'disabled'


    def update_arguments(self):
        """
        Updates the values representing the arguments passed to the get
        method, based on whether or not the 2nd positional argument is
        active and the slider positions.
        """

        _start_line_no = self.position_frames['start'].line.slider.get()
        _start_col_no = self.position_frames['start'].column.slider.get()
        self.start_arg = "{}.{}".format(_start_line_no, _start_col_no)
        if self._is_two_args.var.get():
            _end_line_no = self.position_frames['end'].line.slider.get()
            _end_col_no = self.position_frames['end'].column.slider.get()
            self.end_arg = "{}.{}".format(_end_line_no, _end_col_no)
        else:
            self.end_arg = None
        self._update_method_labels()
        self._select()


    def _update_method_labels(self):
        if self.end_arg:
            for _key in self.position_frames:
                _string = "text.get('{}', '{}')".format(
                                                self.start_arg, self.end_arg)
                self.position_frames[_key].label['text'] = _string
        else:
            _string = "text.get('{}')".format(self.start_arg)
            self.position_frames['start'].label['text'] = _string


    def _select(self):
        self.text.focus_set()
        self.text.tag_remove('sel', '1.0', 'end')
        self.text.tag_add('sel', self.start_arg, self.end_arg)
        if self.end_arg:
            self.text.mark_set('insert', self.end_arg)
        else:
            self.text.mark_set('insert', self.start_arg)


class TextWithStats(tk.Text):
    """
    Text widget that stores stats of its content:
    self.line_count:        the total number of lines
    self.lines_length:      the total number of characters per line
    self.update_callback:   can be set as the reference to the callback
                            to be called with each update
    """

    def __init__(self, master, update_callback=None, *args, **kwargs):
        tk.Text.__init__(self, master, *args, **kwargs)
        self._events = ('<KeyPress>',
                        '<KeyRelease>',
                        '<ButtonRelease-1>',
                        '<ButtonRelease-2>',
                        '<ButtonRelease-3>',
                        '<Delete>',
                        '<<Cut>>',
                        '<<Paste>>',
                        '<<Undo>>',
                        '<<Redo>>')
        self.line_count = None
        self.lines_length = list()
        self.update_callback = update_callback
        self.update_stats()
        self.bind_events_on_widget_to_callback( self._events,
                                                self,
                                                self.update_stats)


    @staticmethod
    def bind_events_on_widget_to_callback(events, widget, callback):
        """
        Bind events on widget to callback.
        """

        for _event in events:
            widget.bind(_event, callback)


    def update_stats(self, event=None):
        """
        Update self.line_count, self.lines_length stats and call
        self.update_callback.
        """

        _string = self.get('1.0', 'end-1c')
        _string_lines = _string.splitlines()
        self.line_count = len(_string_lines)
        del self.lines_length[:]
        for _line in _string_lines:
            self.lines_length.append(len(_line))
        if self.update_callback:
            self.update_callback()


class PositionFrame(tk.LabelFrame):
    """
    A LabelFrame that has two LabelFrames which has Scales.
    """

    def __init__(self, master, *args, **kwargs):
        tk.LabelFrame.__init__(self, master, *args, **kwargs)
        self._create_widgets()
        self._layout()


    def _create_widgets(self):
        self.line = SliderFrame(self, orient='vertical', text="line=")
        self.column = SliderFrame(self, orient='horizontal', text="column=")
        self.label = tk.Label(self, text="Label")


    def _layout(self):
        self.line.grid(sticky='ns', row=0, column=0, rowspan=2)
        self.column.grid(sticky='ew', row=0, column=1, columnspan=2)
        self.label.grid(sticky='nsew', row=1, column=1)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)


class SliderFrame(tk.LabelFrame):
    """
    A LabelFrame that encapsulates a Scale.
    """

    def __init__(self, master, orient, *args, **kwargs):
        tk.LabelFrame.__init__(self, master, *args, **kwargs)

        self.slider = tk.Scale(self, orient=orient)
        self.slider.pack(fill='both', expand=True)


if __name__ == '__main__':
    root = tk.Tk()
    demo = Demo(root, text="text.get(start, end=None)")

    with open(__file__) as f:
        demo.text.insert('1.0', f.read())
    demo.text.update_stats()
    demo.pack(fill='both', expand=True)
    root.mainloop()

Is nested function a good approach when required by only one function?

A function inside of a function is commonly used for closures.

(There is a lot of contention over what exactly makes a closure a closure.)

Here's an example using the built-in sum(). It defines start once and uses it from then on:

def sum_partial(start):
    def sum_start(iterable):
        return sum(iterable, start)
    return sum_start

In use:

>>> sum_with_1 = sum_partial(1)
>>> sum_with_3 = sum_partial(3)
>>> 
>>> sum_with_1
<function sum_start at 0x7f3726e70b90>
>>> sum_with_3
<function sum_start at 0x7f3726e70c08>
>>> sum_with_1((1,2,3))
7
>>> sum_with_3((1,2,3))
9

Built-in python closure

functools.partial is an example of a closure.

From the python docs, it's roughly equivalent to:

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

(Kudos to @user225312 below for the answer. I find this example easier to figure out, and hopefully will help answer @mango's comment.)

C++ Redefinition Header Files (winsock2.h)

In my project (I use VS 2008 SP1) works next solution:

Header file:

//myclass.h
#pragma once
#define _WINSOCKAPI_
#include <windows.h>

Cpp class:

//myclass.cpp
#include "Util.h"
#include "winsock2class.h"
#pragma comment(lib, "Ws2_32.lib")

where #include "winsock2class.h" mean class which implemented winsock2.h :

//winsock2class.h
#include <winsock2.h>
#include <windows.h>
#pragma comment(lib, "Ws2_32.lib")

UITableView example for Swift

For completeness sake, and for those that do not wish to use the Interface Builder, here's a way of creating the same table as in Suragch's answer entirely programatically - albeit with a different size and position.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    var tableView: UITableView = UITableView()
    let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    let cellReuseIdentifier = "cell"

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.frame = CGRectMake(0, 50, 320, 200)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return animals.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

        cell.textLabel?.text = animals[indexPath.row]

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }

}

Make sure you have remembered to import UIKit.

How can I force browsers to print background images in CSS?

it is working in google chrome when you add !important attribute to background image make sure you add attribute first and try again, you can do it like that

    .inputbg {
background: url('inputbg.png') !important;  

}

Find closing HTML tag in Sublime Text

Try Emmet plug-in command Go To Matching Pair:

http://docs.emmet.io/actions/go-to-pair/

Shortcut (Mac): Shift + Control + T

Shortcut (PC): Control + Alt + J

https://github.com/sergeche/emmet-sublime#available-actions

How do I change JPanel inside a JFrame on the fly?

I suggest you to add both panel at frame creation, then change the visible panel by calling setVisible(true/false) on both. When calling setVisible, the parent will be notified and asked to repaint itself.

How to access the elements of a function's return array?

<?php
function demo($val,$val1){
    return $arr=array("value"=>$val,"value1"=>$val1);

}
$arr_rec=demo(25,30);
echo $arr_rec["value"];
echo $arr_rec["value1"];
?>

How to check if variable is array?... or something array-like

You can check instance of Traversable with a simple function. This would work for all this of Iterator because Iterator extends Traversable

function canLoop($mixed) {
    return is_array($mixed) || $mixed instanceof Traversable ? true : false;
}

Getting Current time to display in Label. VB.net

Try This.....

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

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub

Android eclipse DDMS - Can't access data/data/ on phone to pull files

When I say file system I meant the whole file system. But you can only browse part of the file system on a retail phone, perhaps even most of file system but not ./data. Sorry for any confusion this may have caused.

This is alarming to me because I have a rooted my retail Nexus One and a developer/unlocked Nexus One. Since I rooted my retail Nexus One I can't figure out why I can't browse the whole file system like I can on my developer Nexus One.

WPF: Grid with column/row margin/padding?

Sometimes the simple method is the best. Just pad your strings with spaces. If it is only a few textboxes etc this is by far the simplest method.

You can also simply insert blank columns/rows with a fixed size. Extremely simple and you can easily change it.

Efficient way to return a std::vector in c++

   vector<string> func1() const
   {
      vector<string> parts;
      return vector<string>(parts.begin(),parts.end()) ;
   } 

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes '20201231' but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME) to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:

CREATE TABLE dbo.T(D DATETIME)

--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')

Warnings in the execution plan

--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))

No warnings

Efficiently updating database using SQLAlchemy ORM

If it is because of the overhead in terms of creating objects, then it probably can't be sped up at all with SA.

If it is because it is loading up related objects, then you might be able to do something with lazy loading. Are there lots of objects being created due to references? (IE, getting a Company object also gets all of the related People objects).

How to change the size of the font of a JLabel to take the maximum size

 JLabel textLabel = new JLabel("<html><span style='font-size:20px'>"+Text+"</span></html>");

Edit a specific Line of a Text File in C#

You can't rewrite a line without rewriting the entire file (unless the lines happen to be the same length). If your files are small then reading the entire target file into memory and then writing it out again might make sense. You can do that like this:

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        int line_to_edit = 2; // Warning: 1-based indexing!
        string sourceFile = "source.txt";
        string destinationFile = "target.txt";

        // Read the appropriate line from the file.
        string lineToWrite = null;
        using (StreamReader reader = new StreamReader(sourceFile))
        {
            for (int i = 1; i <= line_to_edit; ++i)
                lineToWrite = reader.ReadLine();
        }

        if (lineToWrite == null)
            throw new InvalidDataException("Line does not exist in " + sourceFile);

        // Read the old file.
        string[] lines = File.ReadAllLines(destinationFile);

        // Write the new file over the old file.
        using (StreamWriter writer = new StreamWriter(destinationFile))
        {
            for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
            {
                if (currentLine == line_to_edit)
                {
                    writer.WriteLine(lineToWrite);
                }
                else
                {
                    writer.WriteLine(lines[currentLine - 1]);
                }
            }
        }
    }
}

If your files are large it would be better to create a new file so that you can read streaming from one file while you write to the other. This means that you don't need to have the whole file in memory at once. You can do that like this:

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        int line_to_edit = 2;
        string sourceFile = "source.txt";
        string destinationFile = "target.txt";
        string tempFile = "target2.txt";

        // Read the appropriate line from the file.
        string lineToWrite = null;
        using (StreamReader reader = new StreamReader(sourceFile))
        {
            for (int i = 1; i <= line_to_edit; ++i)
                lineToWrite = reader.ReadLine();
        }

        if (lineToWrite == null)
            throw new InvalidDataException("Line does not exist in " + sourceFile);

        // Read from the target file and write to a new file.
        int line_number = 1;
        string line = null;
        using (StreamReader reader = new StreamReader(destinationFile))
        using (StreamWriter writer = new StreamWriter(tempFile))
        {
            while ((line = reader.ReadLine()) != null)
            {
                if (line_number == line_to_edit)
                {
                    writer.WriteLine(lineToWrite);
                }
                else
                {
                    writer.WriteLine(line);
                }
                line_number++;
            }
        }

        // TODO: Delete the old file and replace it with the new file here.
    }
}

You can afterwards move the file once you are sure that the write operation has succeeded (no excecption was thrown and the writer is closed).

Note that in both cases it is a bit confusing that you are using 1-based indexing for your line numbers. It might make more sense in your code to use 0-based indexing. You can have 1-based index in your user interface to your program if you wish, but convert it to a 0-indexed before sending it further.

Also, a disadvantage of directly overwriting the old file with the new file is that if it fails halfway through then you might permanently lose whatever data wasn't written. By writing to a third file first you only delete the original data after you are sure that you have another (corrected) copy of it, so you can recover the data if the computer crashes halfway through.

A final remark: I noticed that your files had an xml extension. You might want to consider if it makes more sense for you to use an XML parser to modify the contents of the files instead of replacing specific lines.

How to store .pdf files into MySQL as BLOBs using PHP?

//Pour inserer :
            $pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
            $filetype = addslashes($_FILES['inputname']['type']);//pour le test 
            $namepdf = addslashes($_FILES['inputname']['name']);            
            if (substr($filetype, 0, 11) == 'application'){
            $mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
            }
//Pour afficher :
            $row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
            foreach($row as $result){
                 $file=$result['pdf'];
            }
            header('Content-type: application/pdf');
            echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));

GROUP BY having MAX date

Another way that doesn't use group by:

SELECT * FROM tblpm n 
  WHERE date_updated=(SELECT date_updated FROM tblpm n 
                        ORDER BY date_updated desc LIMIT 1)

How to pass an object into a state using UI-router?

Btw you can also use the ui-sref attribute in your templates to pass objects

ui-sref="myState({ myParam: myObject })"

How can I disable an <option> in a <select> based on its value in JavaScript?

Pure Javascript

With pure Javascript, you'd have to cycle through each option, and check the value of it individually.

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  (op[i].value.toLowerCase() == "stackoverflow") 
    ? op[i].disabled = true 
    : op[i].disabled = false ;
}

Without enabling non-targeted elements:

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  if (op[i].value.toLowerCase() == "stackoverflow") {
    op[i].disabled = true;
  }
}

jQuery

With jQuery you can do this with a single line:

$("option[value='stackoverflow']")
  .attr("disabled", "disabled")
  .siblings().removeAttr("disabled");

Without enabling non-targeted elements:

$("option[value='stackoverflow']").attr("disabled", "disabled");

? Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
  }
});

Without enabling non-targeted elements:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled");
  }
});

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

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

Meta tags are not a reliable way to achieve this result. Generally you shouldn't even do this - it should be left up to the user/user agent to decide what do to with the content you provide. The user can always force their browser to download the file if they wish to.

If you still want to force the browser to download the file, modify the HTTP headers directly. Here's a PHP code example:

$path = "path/to/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes');  // Allow support for download resume
header('Content-Length: ' . filesize($path));  // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf');  // Change the mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
readfile($path);  // This is necessary in order to get it to actually download the file, otherwise it will be 0Kb

Note that this is just an extension to the HTTP protocol; some browsers might ignore it anyway.

How to get a substring between two strings in PHP?

function img($n,$str){

    $first=$n."tag/";
    $n+=1;
    $last=$n."tag/";
    $frm = stripos($str,$first);
    $to = stripos($str,$last);
    echo $frm."<br>";
    echo $to."<br>";
    $to=($to=="")?(strlen($str)-$frm):($to-$frm);
    $final = substr($str,$frm,$to);
    echo $to."<br>";
    echo $final."<br>";

}


$str = "1tag/Ilove.php2tag/youlike.java3tag/youlike.php";
img(1,$str);

img(2,$str);

img(3,$str);

Eclipse Workspaces: What for and why?

The whole point of a workspace is to group a set of related projects together that usually make up an application. The workspace framework comes down to the eclipse.core.resources plugin and it naturally by design makes sense.

Projects have natures, builders are attached to specific projects and as you change resources in one project you can see in real time compile or other issues in projects that are in the same workspace. So the strategy I suggest is have different workspaces for different projects you work on but without a workspace in eclipse there would be no concept of a collection of projects and configurations and after all it's an IDE tool.

If that does not make sense ask how Net Beans or Visual Studio addresses this? It's the same theme. Maven is a good example, checking out a group of related maven projects into a workspace lets you develop and see errors in real time. If not a workspace what else would you suggest? An RCP application can be a different beast depending on what its used for but in the true IDE sense I don't know what would be a better solution than a workspace or context of projects. Just my thoughts. - Duncan

JPanel Padding in Java

I will suppose your JPanel contains JTextField, for the sake of the demo.

Those components provides JTextComponent#setMargin() method which seems to be what you're looking for.

If you're looking for an empty border of any size around your text, well, use EmptyBorder

Git merge two local branches

Here's a clear picture:

Assuming we have branch-A and branch-B

We want to merge branch-B into branch-A

on branch-B -> A: switch to branch-A

on branch-A: git merge branch-B

Clearing an HTML file upload field via JavaScript

For compatibility when ajax is not available, set .val('') or it will resend the last ajax-uploaded file that is still present in the input. The following should properly clear the input whilst retaining .on() events:

var input = $("input[type='file']");
input.html(input.html()).val('');

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

What's the difference between emulation and simulation?

Both are models of an object that you have some means of controlling inputs and observing outputs. With an emulator, you want the output to be exactly what the object you are emulating would produce. With a simulator, you want certain properties of your output to be similar to what the object would produce.

Let me give an example -- suppose you want to do some system testing to see how adding a new sensor (like a thermometer) to a system would affect the system. You know that the thermometer sends a message 8 time a second containing its measurement.

Simulation -- if you do not have the thermometer yet, but you want to test that this message rate will not overload you system, you can simulate the sensor by attaching a unit that sends a random number 8 times a second. You can run any test that does not rely on the actual value the sensor sends.

Emulation -- suppose you have a very expensive thermometer that measures to 0.001 C, and you want to see if you can get by with a cheaper thermometer that only measures to the nearest 0.5 C. You can emulate the cheaper thermometer using an expensive thermometer by rounding the reading to the nearest 0.5 C and running tests that rely on the temperature values.

How to directly execute SQL query in C#?

IMPORTANT NOTE: You should not concatenate SQL queries unless you trust the user completely. Query concatenation involves risk of SQL Injection being used to take over the world, ...khem, your database.

If you don't want to go into details how to execute query using SqlCommand then you could call the same command line like this:

string userInput = "Brian";
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format(@"sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS  
     -s ; -W -w 100 -Q "" SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName,
     tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '{0}' """, userInput);

process.StartInfo = startInfo;
process.Start();

Just ensure that you escape each double quote " with ""

How to view the assembly behind the code using Visual C++?

There are several approaches:

  1. You can normally see assembly code while debugging C++ in visual studio (and eclipse too). For this in Visual Studio put a breakpoint on code in question and when debugger hits it rigth click and find "Go To Assembly" ( or press CTRL+ALT+D )

  2. Second approach is to generate assembly listings while compiling. For this go to project settings -> C/C++ -> Output Files -> ASM List Location and fill in file name. Also select "Assembly Output" to "Assembly With Source Code".

  3. Compile the program and use any third-party debugger. You can use OllyDbg or WinDbg for this. Also you can use IDA (interactive disassembler). But this is hardcore way of doing it.

Select tableview row programmatically

Use this category to select a table row and execute a given segue after a delay.
Call this within your viewDidAppear method:

[tableViewController delayedSelection:withSegueIdentifier:]


@implementation UITableViewController (TLUtils)

-(void)delayedSelection:(NSIndexPath *)idxPath withSegueIdentifier:(NSString *)segueID {
    if (!idxPath) idxPath = [NSIndexPath indexPathForRow:0 inSection:0];                                                                                                                                                                 
    [self performSelector:@selector(selectIndexPath:) withObject:@{@"NSIndexPath": idxPath, @"UIStoryboardSegue": segueID } afterDelay:0];                                                                                               
}

-(void)selectIndexPath:(NSDictionary *)args {
    NSIndexPath *idxPath = args[@"NSIndexPath"];                                                                                                                                                                                         
    [self.tableView selectRowAtIndexPath:idxPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];                                                                                                                            

    if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)])
        [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:idxPath];                                                                                                                                              

    [self performSegueWithIdentifier:args[@"UIStoryboardSegue"] sender:self];                                                                                                                                                            
}

@end

Properly close mongoose's connection once you're done

You will get an error if you try to close/disconnect outside of the method. The best solution is to close the connection in both callbacks in the method. The dummy code is here.

const newTodo = new Todo({text:'cook dinner'});

newTodo.save().then((docs) => {
  console.log('todo saved',docs);
  mongoose.connection.close();
},(e) => {
  console.log('unable to save');
});

List all sequences in a Postgres db 8.1 with SQL

after a little bit of pain, i got it.

the best way to achieve this is to list all tables

select * from pg_tables where schemaname = '<schema_name>'

and then, for each table, list all columns with attributes

select * from information_schema.columns where table_name = '<table_name>'

then, for each column, test if it has a sequence

select pg_get_serial_sequence('<table_name>', '<column_name>')

and then, get the information about this sequence

select * from <sequence_name>

Most efficient way to check for DBNull and then assign to a variable?

I always use :

if (row["value"] != DBNull.Value)
  someObject.Member = row["value"];

Found it short and comprehensive.

Allow anonymous authentication for a single folder in web.config?

<location path="ForAll/Demo.aspx">
 <system.web>
  <authorization>
    <allow users="*" />
  </authorization>
 </system.web>
</location>

In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

How to reset or change the passphrase for a GitHub SSH key?

You can change the passphrase for your private key by doing:

ssh-keygen -f ~/.ssh/id_rsa -p

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

You're doing a few things wrong.

  1. First, browserHistory isn't a thing in V4, so you can remove that.

  2. Second, you're importing everything from react-router, it should be react-router-dom.

  3. Third, react-router-dom doesn't export a Router, instead, it exports a BrowserRouter so you need to import { BrowserRouter as Router } from 'react-router-dom.

Looks like you just took your V3 app and expected it to work with v4, which isn't a great idea.

How to get the EXIF data from a file using C#

As suggested, you can use some 3rd party library, or do it manually (which is not that much work), but the simplest and the most flexible is to perhaps use the built-in functionality in .NET. For more see:

I say "it’s the most flexible" because .NET does not try to interpret or coalesce the data in any way. For each EXIF you basically get an array of bytes. This may be good or bad depending on how much control you actually want.

Also, I should point out that the property list does not in fact directly correspond to the EXIF values. EXIF itself is stored in multiple tables with overlapping ID’s, but .NET puts everything in one list and redefines ID’s of some items. But as long as you don’t care about the precise EXIF ID’s, you should be fine with the .NET mapping.


Edit: It's possible to do it without loading the full image following this answer: https://stackoverflow.com/a/552642/2097240

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

I have had the same issue that I solved this way:

Instead of adding the meta to the current page header that caused the same error as you had:

Page.Header.Controls.Add(meta);

I used this instead:

 Master.FindControl("YourHeadContentPlaceHolder").Controls.Add(meta);

and it works like a charm.

How to merge many PDF files into a single one?

You can use http://www.mergepdf.net/ for example

Or:

PDFTK http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/

If you are NOT on Ubuntu and you have the same problem (and you wanted to start a new topic on SO and SO suggested to have a look at this question) you can also do it like this:

Things You'll Need:

* Full Version of Adobe Acrobat
  1. Open all the .pdf files you wish to merge. These can be minimized on your desktop as individual tabs.

  2. Pull up what you wish to be the first page of your merged document.

  3. Click the 'Combine Files' icon on the top left portion of the screen.

  4. The 'Combine Files' window that pops up is divided into three sections. The first section is titled, 'Choose the files you wish to combine'. Select the 'Add Open Files' option.

  5. Select the other open .pdf documents on your desktop when prompted.

  6. Rearrange the documents as you wish in the second window, titled, 'Arrange the files in the order you want them to appear in the new PDF'

  7. The final window, titled, 'Choose a file size and conversion setting' allows you to control the size of your merged PDF document. Consider the purpose of your new document. If its to be sent as an e-mail attachment, use a low size setting. If the PDF contains images or is to be used for presentation, choose a high setting. When finished, select 'Next'.

  8. A final choice: choose between either a single PDF document, or a PDF package, which comes with the option of creating a specialized cover sheet. When finished, hit 'Create', and save to your preferred location.

    • Tips & Warnings

Double check the PDF documents prior to merging to make sure all pertinent information is included. Its much easier to re-create a single PDF page than a multi-page document.

How should I pass an int into stringWithFormat?

Don't forget for long long int:

long long int id = [obj.id longLongValue];
[NSString stringWithFormat:@"this is my id: %lld", id]

Closing WebSocket correctly (HTML5, Javascript)

According to the protocol spec v76 (which is the version that browser with current support implement):

To close the connection cleanly, a frame consisting of just a 0xFF byte followed by a 0x00 byte is sent from one peer to ask that the other peer close the connection.

If you are writing a server, you should make sure to send a close frame when the server closes a client connection. The normal TCP socket close method can sometimes be slow and cause applications to think the connection is still open even when it's not.

The browser should really do this for you when you close or reload the page. However, you can make sure a close frame is sent by doing capturing the beforeunload event:

window.onbeforeunload = function() {
    websocket.onclose = function () {}; // disable onclose handler first
    websocket.close();
};

I'm not sure how you can be getting an onclose event after the page is refreshed. The websocket object (with the onclose handler) will no longer exist once the page reloads. If you are immediately trying to establish a WebSocket connection on your page as the page loads, then you may be running into an issue where the server is refusing a new connection so soon after the old one has disconnected (or the browser isn't ready to make connections at the point you are trying to connect) and you are getting an onclose event for the new websocket object.

What is the difference between Left, Right, Outer and Inner Joins?

There are three basic types of join:

  • INNER join compares two tables and only returns results where a match exists. Records from the 1st table are duplicated when they match multiple results in the 2nd. INNER joins tend to make result sets smaller, but because records can be duplicated this isn't guaranteed.
  • CROSS join compares two tables and return every possible combination of rows from both tables. You can get a lot of results from this kind of join that might not even be meaningful, so use with caution.
  • OUTER join compares two tables and returns data when a match is available or NULL values otherwise. Like with INNER join, this will duplicate rows in the one table when it matches multiple records in the other table. OUTER joins tend to make result sets larger, because they won't by themselves remove any records from the set. You must also qualify an OUTER join to determine when and where to add the NULL values:
    • LEFT means keep all records from the 1st table no matter what and insert NULL values when the 2nd table doesn't match.
    • RIGHT means the opposite: keep all records from the 2nd table no matter what and insert NULL values whent he 1st table doesn't match.
    • FULL means keep all records from both tables, and insert a NULL value in either table if there is no match.

Often you see will the OUTER keyword omitted from the syntax. Instead it will just be "LEFT JOIN", "RIGHT JOIN", or "FULL JOIN". This is done because INNER and CROSS joins have no meaning with respect to LEFT, RIGHT, or FULL, and so these are sufficient by themselves to unambiguously indicate an OUTER join.

Here is an example of when you might want to use each type:

  • INNER: You want to return all records from the "Invoice" table, along with their corresponding "InvoiceLines". This assumes that every valid Invoice will have at least one line.
  • OUTER: You want to return all "InvoiceLines" records for a particular Invoice, along with their corresponding "InventoryItem" records. This is a business that also sells service, such that not all InvoiceLines will have an IventoryItem.
  • CROSS: You have a digits table with 10 rows, each holding values '0' through '9'. You want to create a date range table to join against, so that you end up with one record for each day within the range. By CROSS-joining this table with itself repeatedly you can create as many consecutive integers as you need (given you start at 10 to 1st power, each join adds 1 to the exponent). Then use the DATEADD() function to add those values to your base date for the range.

adding and removing classes in angularJs using ng-click

you can also do that in a directive, if you want to remove the previous class and add a new class

    .directive('toggleClass', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                if(element.attr("class") == "glyphicon glyphicon-pencil") {
                    element.removeClass("glyphicon glyphicon-pencil");
                    element.addClass(attrs.toggleClass);
                } else {
                    element.removeClass("glyphicon glyphicon-ok");
                    element.addClass("glyphicon glyphicon-pencil");
                }
            });
        }
    };
});

and in your template:

<i class="glyphicon glyphicon-pencil" toggle-class="glyphicon glyphicon-ok"></i>

Bootstrap full-width text-input within inline-form

As stated in a similar question, try removing instances of the input-group class and see if that helps.

refering to bootstrap:

Individual form controls automatically receive some global styling. All textual , , and elements with .form-control are set to width: 100%; by default. Wrap labels and controls in .form-group for optimum spacing.

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

How to create a numeric vector of zero length in R

Simply:

x <- vector(mode="numeric", length=0)

How to Replace Multiple Characters in SQL?

I had a one-off data migration issue where the source data could not output correctly some unusual/technical characters plus the ubiquitous extra commas in CSVs.

We decided that for each such character the source extract should replace them with something that was recognisable to both the source system and the SQL Server that was loading them but which would not be in the data otherwise.

It did mean however that in various columns across various tables these replacement characters would appear and I would have to replace them. Nesting multiple REPLACE functions made the import code look scary and prone to errors in misjudging the placement and number of brackets so I wrote the following function. I know it can process a column in a table of 3,000 rows in less than a second though I'm not sure how quickly it will scale up to multi-million row tables.

create function [dbo].[udf_ReplaceMultipleChars]
(
    @OriginalString nvarchar(4000)
  , @ReplaceTheseChars nvarchar(100)
  , @LengthOfReplacement int = 1
)
returns nvarchar(4000)
begin

    declare @RevisedString nvarchar(4000) = N'';
    declare @lengthofinput int =
            (
            select len(@OriginalString)
            );

with AllNumbers
as (select 1 as  Number
    union all
    select Number + 1
    from AllNumbers
    where Number < @lengthofinput)
select @RevisedString += case
                             when (charindex(substring(@OriginalString, Number, 1), @ReplaceTheseChars, 1) - 1) % 2
    = 0 then
                                 substring(
                                              @ReplaceTheseChars
                                            , charindex(
                                                           substring(@OriginalString, Number, 1)
                                                         , @ReplaceTheseChars
                                                         , 1
                                                       ) + 1
                                            , @LengthOfReplacement
                                          )
                             else
                                 substring(@OriginalString, Number, 1)
                         end
    from AllNumbers
    option (maxrecursion 4000);
    return (@RevisedString);
end;

It works by submitting both the string to be evaluated and have characters to be replaced (@OriginalString) along with a string of paired characters where the first character is to be replaced by the second, the third by the fourth, fifth by sixth and so on (@ReplaceTheseChars).

Here is the string of chars that I needed to replace and their replacements... [']"~,{Ø}°$±|¼¦¼ª½¬½^¾#?

i.e. A opening square bracket denotes an apostrophe, a closing one a double quote. You can see that there were vulgar fractions as well as degrees and diameter symbols in there.

There is a default @LengthOfReplacement that is included as a starting point if anyone needed to replace longer strings. I played around with that in my project but the single char replacement was the main function.

The condition of the case statement is important. It ensures that it only replaces the character if it is found in your @ReplaceTheseChars variable and that the character has to be found in an odd numbered position (the minus 1 from charindex result ensures that anything NOT found returns a negative modulo value). i.e if you find a tilde (~) in position 5 it will replace it with a comma but if on a subsequent run it found the comma in position 6 it would not replace it with a curly bracket ({).

This can be best demonstrated with an example...

declare @ProductDescription nvarchar(20) = N'abc~def[¦][123';
select @ProductDescription
= dbo.udf_ReplaceMultipleChars(
                                  @ProductDescription
/* NB the doubling up of the apostrophe is necessary in the string but resolves to a single apostrophe when passed to the function */
                                ,'['']"~,{Ø}°$±|¼¦¼ª½¬½^¾#?' 
                                , default
                              );
select @ProductDescription
 , dbo.udf_ReplaceMultipleChars(
                                   @ProductDescription
                                 ,'['']"~,{Ø}°$±|¼¦¼ª½¬½^¾#?'
/* if you didn't know how to type those peculiar chars in then you can build a string like  this... '[' + nchar(0x0027) + ']"~,{' + nchar(0x00D8) + '}' + nchar(0x00B0) etc */
                                ,
                                 default
                               );

This will return both the value after the first pass through the function and the second time as follows... abc,def'¼"'123 abc,def'¼"'123

A table update would just be

update a
set a.Col1 = udf.ReplaceMultipleChars(a.Col1,'~,]"',1)
from TestTable a

Finally (I hear you say!), although I've not had access to the translate function I believe that this function can process the example shown in the documentation quite easily. The TRANSLATE function demo is

SELECT TRANSLATE('2*[3+4]/{7-2}', '[]{}', '()()');

which returns 2*(3+4)/(7-2) although I understand it might not work on 2*[3+4]/[7-2] !!

My function would approach this as follows listing each char to be replaced followed by its replacement [ --> (, { --> ( etc.

select dbo.udf_ReplaceMultipleChars('2*[3+4]/{7-2}', '[({(])})', 1);

which will also work for

select dbo.udf_ReplaceMultipleChars('2*[3+4]/[7-2]', '[({(])})', 1);

I hope someone finds this useful and if you get to test its performance against larger tables do let us know one way or another!

Error Importing SSL certificate : Not an X.509 Certificate

This seems like an old thread, but I'll add my experience here. I tried to install a cert as well and got that error. I then opened the cer file with a txt editor, and noticed that there is an extra space (character) at the end of each line. Removing those lines allowed me to import the cert.

Hope this is worth something to someone else.

What is the @Html.DisplayFor syntax for?

After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class

    <td>
    myClassNameProperty
    </td>
   <td>
    myClassNameProperty, This is direct from Item
    </td>

This is the generated HTML from below code

<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)            
</td>

<td>
@item.Genre.Name, This is direct from Item
</td>

At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least

i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below

@item.Genre.Name
@item.Genre.Id
@item.Genre.Description

and so on depending on number of properties.

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

In my case,

image = cv2.imread(filepath)
final_img = cv2.resize(image, size_img)

filepath was incorrect, cv2.imshow didn't give any error in this case but due to wrong path cv2.resize was giving me error.

How do you validate a URL with a regular expression in Python?

http://pypi.python.org/pypi/rfc3987 gives regular expressions for consistency with the rules in RFC 3986 and RFC 3987 (that is, not with scheme-specific rules).

A regexp for IRI_reference is:

(?P<scheme>[a-zA-Z][a-zA-Z0-9+.-]*):(?://(?P<iauthority>(?:(?P<iuserinfo>(?:(?:[
a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U0002
0000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U
00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009ff
fd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U00
0dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:)*)@)?(?P<ihost>\
\[(?:(?:[0-9A-F]{1,4}:){6}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4]
[0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|::(?:[0
-9A-F]{1,4}:){5}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]
?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|[0-9A-F]{1,4}?::(
?:[0-9A-F]{1,4}:){4}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|
[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F
]{1,4}:)?[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){3}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?
:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[
0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,2}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){2}(?:
[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3
}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,3}[0-9A-F]{1,
4})?::(?:[0-9A-F]{1,4}:)(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0
-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-
9A-F]{1,4}:){,4}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]
|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|
(?:(?:[0-9A-F]{1,4}:){,5}[0-9A-F]{1,4})?::[0-9A-F]{1,4}|(?:(?:[0-9A-F]{1,4}:){,6
}[0-9A-F]{1,4})?::|v[0-9A-F]+\\.(?:[a-zA-Z0-9_.~-]|[!$&'()*+,;=]|:)+)\\]|(?:(?:(
?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][
0-9]?))|(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\
U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U000500
00-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00
090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd
\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=])*)(
?::(?P<port>[0-9]*))?)(?P<ipath>(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\uf
dcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\
U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007f
ffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U0
00bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-
F][0-9A-F]|[!$&'()*+,;=]|:|@)*)*)|(?P<ipath>/(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7
ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000
-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U0007
0000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U
000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000eff
fd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)+(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff
\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\
U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U000700
00-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U00
0b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd
])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)*)*)?)|(?P<ipath>(?:(?:[a-zA-Z0-9._~-]|[\
xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U
00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006ff
fd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U00
0afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-
\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)+(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa
0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00
030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd
\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000a
fffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U
000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)*)*)|(?P<ipath>))(?:\\?(?P<iquery
>(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U000
1fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\
U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U000900
00-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U00
0d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)|[\
ue000-\uf8ff\U000f0000-\U000ffffd\U00100000-\U0010fffd]|/|\\?)*))?(?:\\#(?P<ifra
gment>(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-
\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050
000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U0
0090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfff
d\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|
@)|/|\\?)*))?|(?:(?://(?P<iauthority>(?:(?P<iuserinfo>(?:(?:[a-zA-Z0-9._~-]|[\xa
0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00
030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd
\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000a
fffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U
000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:)*)@)?(?P<ihost>\\[(?:(?:[0-9A-F]{1,
4}:){6}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-
9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|::(?:[0-9A-F]{1,4}:){5}(?:
[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3
}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|[0-9A-F]{1,4}?::(?:[0-9A-F]{1,4}:){4
}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\
.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:)?[0-9A-F]{1
,4})?::(?:[0-9A-F]{1,4}:){3}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-
4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?
:[0-9A-F]{1,4}:){,2}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){2}(?:[0-9A-F]{1,4}:[0-9A
-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][
0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,3}[0-9A-F]{1,4})?::(?:[0-9A-F]{1
,4}:)(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]
?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,4}[0-
9A-F]{1,4})?::(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[
0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}
:){,5}[0-9A-F]{1,4})?::[0-9A-F]{1,4}|(?:(?:[0-9A-F]{1,4}:){,6}[0-9A-F]{1,4})?::|
v[0-9A-F]+\\.(?:[a-zA-Z0-9_.~-]|[!$&'()*+,;=]|:)+)\\]|(?:(?:(?:25[0-5]|2[0-4][0-
9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(?:(?:[a-zA
-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000
-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U0006
0000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U
000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dff
fd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=])*)(?::(?P<port>[0-9]*)
)?)(?P<ipath>(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U0
0010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fff
d\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U000
8fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\
U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*
+,;=]|:|@)*)*)|(?P<ipath>/(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufd
f0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U000400
00-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00
080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd
\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A
-F]|[!$&'()*+,;=]|:|@)+(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0
-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000
-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U0008
0000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U
000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F
]|[!$&'()*+,;=]|:|@)*)*)?)|(?P<ipath>(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\u
fdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd
\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007
fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U
000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A
-F][0-9A-F]|[!$&'()*+,;=]|@)+(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf
\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00
040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd
\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000b
fffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][
0-9A-F]|[!$&'()*+,;=]|:|@)*)*)|(?P<ipath>))(?:\\?(?P<iquery>(?:(?:(?:[a-zA-Z0-9.
_~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U000
2fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\
U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a00
00-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U00
0e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)|[\ue000-\uf8ff\U000f000
0-\U000ffffd\U00100000-\U0010fffd]|/|\\?)*))?(?:\\#(?P<ifragment>(?:(?:(?:[a-zA-
Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-
\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060
000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U0
00a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfff
d\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)|/|\\?)*))?)

In one line:

(?P<scheme>[a-zA-Z][a-zA-Z0-9+.-]*):(?://(?P<iauthority>(?:(?P<iuserinfo>(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:)*)@)?(?P<ihost>\\[(?:(?:[0-9A-F]{1,4}:){6}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|::(?:[0-9A-F]{1,4}:){5}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|[0-9A-F]{1,4}?::(?:[0-9A-F]{1,4}:){4}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:)?[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){3}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,2}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){2}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,3}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:)(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,4}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,5}[0-9A-F]{1,4})?::[0-9A-F]{1,4}|(?:(?:[0-9A-F]{1,4}:){,6}[0-9A-F]{1,4})?::|v[0-9A-F]+\\.(?:[a-zA-Z0-9_.~-]|[!$&'()*+,;=]|:)+)\\]|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=])*)(?::(?P<port>[0-9]*))?)(?P<ipath>(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)*)*)|(?P<ipath>/(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)+(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)*)*)?)|(?P<ipath>(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)+(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)*)*)|(?P<ipath>))(?:\\?(?P<iquery>(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)|[\ue000-\uf8ff\U000f0000-\U000ffffd\U00100000-\U0010fffd]|/|\\?)*))?(?:\\#(?P<ifragment>(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)|/|\\?)*))?|(?:(?://(?P<iauthority>(?:(?P<iuserinfo>(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:)*)@)?(?P<ihost>\\[(?:(?:[0-9A-F]{1,4}:){6}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|::(?:[0-9A-F]{1,4}:){5}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|[0-9A-F]{1,4}?::(?:[0-9A-F]{1,4}:){4}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:)?[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){3}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,2}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){2}(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,3}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:)(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,4}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:[0-9A-F]{1,4}:){,5}[0-9A-F]{1,4})?::[0-9A-F]{1,4}|(?:(?:[0-9A-F]{1,4}:){,6}[0-9A-F]{1,4})?::|v[0-9A-F]+\\.(?:[a-zA-Z0-9_.~-]|[!$&'()*+,;=]|:)+)\\]|(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=])*)(?::(?P<port>[0-9]*))?)(?P<ipath>(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)*)*)|(?P<ipath>/(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)+(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)*)*)?)|(?P<ipath>(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|@)+(?:/(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)*)*)|(?P<ipath>))(?:\\?(?P<iquery>(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)|[\ue000-\uf8ff\U000f0000-\U000ffffd\U00100000-\U0010fffd]|/|\\?)*))?(?:\\#(?P<ifragment>(?:(?:(?:[a-zA-Z0-9._~-]|[\xa0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\U00010000-\U0001fffd\U00020000-\U0002fffd\U00030000-\U0003fffd\U00040000-\U0004fffd\U00050000-\U0005fffd\U00060000-\U0006fffd\U00070000-\U0007fffd\U00080000-\U0008fffd\U00090000-\U0009fffd\U000a0000-\U000afffd\U000b0000-\U000bfffd\U000c0000-\U000cfffd\U000d0000-\U000dfffd\U000e1000-\U000efffd])|%[0-9A-F][0-9A-F]|[!$&'()*+,;=]|:|@)|/|\\?)*))?)

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

Use win-node-env, For using it just run below command on your cmd or power shell or git bash:

npm install -g win-node-env

After it everything is like Linux.

Drop unused factor levels in a subsetted data frame

Looking at the droplevels methods code in the R source you can see it wraps to factor function. That means you can basically recreate the column with factor function.
Below the data.table way to drop levels from all the factor columns.

library(data.table)
dt = data.table(letters=factor(letters[1:5]), numbers=seq(1:5))
levels(dt$letters)
#[1] "a" "b" "c" "d" "e"
subdt = dt[numbers <= 3]
levels(subdt$letters)
#[1] "a" "b" "c" "d" "e"

upd.cols = sapply(subdt, is.factor)
subdt[, names(subdt)[upd.cols] := lapply(.SD, factor), .SDcols = upd.cols]
levels(subdt$letters)
#[1] "a" "b" "c"

How to check programmatically if an application is installed or not in Android?

Try this

This code is used to check weather your application with package name is installed or not if not then it will open playstore link of your app otherwise your installed app

String your_apppackagename="com.app.testing";
    PackageManager packageManager = getPackageManager();
    ApplicationInfo applicationInfo = null;
    try {
        applicationInfo = packageManager.getApplicationInfo(your_apppackagename, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    if (applicationInfo == null) {
        // not installed it will open your app directly on playstore
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + your_apppackagename)));
    } else {
        // Installed
        Intent LaunchIntent = packageManager.getLaunchIntentForPackage(your_apppackagename);
        startActivity( LaunchIntent );
    }

IE8 support for CSS Media Query

The best solution I've found is Respond.js especially if your main concern is making sure your responsive design works in IE8. It's pretty lightweight at 1kb when min/gzipped and you can make sure only IE8 clients load it:

<!--[if lt IE 9]>
<script src="respond.min.js"></script>
<![endif]-->

It's also the recommended method if you're using bootstrap: http://getbootstrap.com/getting-started/#support-ie8-ie9

How do I find the stack trace in Visual Studio?

While debugging, when you hit a break-point.

CTRL+ALT+C

enter image description here

Share cookie between subdomain and domain

The 2 domains mydomain.com and subdomain.mydomain.com can only share cookies if the domain is explicitly named in the Set-Cookie header. Otherwise, the scope of the cookie is restricted to the request host. (This is referred to as a "host-only cookie". See What is a host only cookie?)

For instance, if you sent the following header from subdomain.mydomain.com, then the cookie won't be sent for requests to mydomain.com:

Set-Cookie: name=value

However if you use the following, it will be usable on both domains:

Set-Cookie: name=value; domain=mydomain.com

This cookie will be sent for any subdomain of mydomain.com, including nested subdomains like subsub.subdomain.mydomain.com.

In RFC 2109, a domain without a leading dot meant that it could not be used on subdomains, and only a leading dot (.mydomain.com) would allow it to be used across multiple subdomains (but not the top-level domain, so what you ask was not possible in the older spec).

However, all modern browsers respect the newer specification RFC 6265, and will ignore any leading dot, meaning you can use the cookie on subdomains as well as the top-level domain.

In summary, if you set a cookie like the second example above from mydomain.com, it would be accessible by subdomain.mydomain.com, and vice versa. This can also be used to allow sub1.mydomain.com and sub2.mydomain.com to share cookies.

See also:

sorting a List of Map<String, String>

if you want to make use of lamdas and make it a bit easier to read

  List<Map<String,String>> results;

  Comparator<Map<String,String>> sortByName = Comparator.comparing(x -> x.get("Name"));

  public void doSomething(){
    results.sort(sortByName)
  }

How to call external url in jquery?

it is Cross-site scripting problem. Common modern browsers doesn't allow to send request to another url.

401 Unauthorized: Access is denied due to invalid credentials

In my case,
My application is developed in MVC and my home controller class was decorated with [Authorize] which was causing this issue.
So I've removed it because my application don't require any authentication.

How to add multiple values to a dictionary key in python?

How about

a["abc"] = [1, 2]

This will result in:

>>> a
{'abc': [1, 2]}

Is that what you were looking for?

Call a stored procedure with parameter in c#

It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.

Also, use a using for all disposable objects, so that you are sure that they are disposed properly:

private void button1_Click(object sender, EventArgs e) {
  using (SqlConnection con = new SqlConnection(dc.Con)) {
    using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
      cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }
}

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

How do I prevent Eclipse from hanging on startup?

I had a similar problem after I updated eclipse on Mavericks. Eventually I found that in the eclipse plugins directory the com.google.gdt.eclipse.login jar had version numbers at the end. I removed the version number from the name and it all started fine :)

How to sort a HashSet?

1. Add all set element in list -> al.addAll(s);
2. Sort all the elements in list using -> Collections.sort(al);


 public class SortSetProblem {
 public static void main(String[] args) {
    ArrayList<String> al = new ArrayList();
    Set<String> s = new HashSet<>();
    s.add("ved");
    s.add("prakash");
    s.add("sharma");
    s.add("apple");
    s.add("ved");
    s.add("banana");
    System.out.println("Before Sorting");
    for (String s1 : s) {
        System.out.print("  " + s1);
    }

    System.out.println("After Sorting");
    al.addAll(s);
    Collections.sort(al);
    for (String set : al) {
        System.out.print(" " + set);
    }
  }
 }

input - ved prakash sharma apple ved banana

Output - apple banana prakash sharma ved

Python how to write to a binary file?

Use pickle, like this: import pickle

Your code would look like this:

import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
    pickle.dump(mybytes, mypicklefile)

To read the data back, use the pickle.load method

What's the best way to add a full screen background image in React Native

_x000D_
_x000D_
import React from 'react';
import { 
  ...
  StyleSheet,
  ImageBackground,
} from 'react-native';

render() {
  return (
    
  <ImageBackground source={require('path/to/img')} style={styles.backgroundImage} >
      <View style={{flex: 1, backgroundColor: 'transparent'}} />
      <View style={{flex: 3,backgroundColor: 'transparent'}} >
  </ImageBackground>
    
  );
}

const styles = StyleSheet.create({
  backgroundImage: {
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
    },
});
_x000D_
_x000D_
_x000D_

The difference between Classes, Objects, and Instances

A class is a blueprint which you use to create objects. An object is an instance of a class - it's a concrete 'thing' that you made using a specific class. So, 'object' and 'instance' are the same thing, but the word 'instance' indicates the relationship of an object to its class.

This is easy to understand if you look at an example. For example, suppose you have a class House. Your own house is an object and is an instance of class House. Your sister's house is another object (another instance of class House).

// Class House describes what a house is
class House {
    // ...
}

// You can use class House to create objects (instances of class House)
House myHouse = new House();
House sistersHouse = new House();

The class House describes the concept of what a house is, and there are specific, concrete houses which are objects and instances of class House.

Note: This is exactly the same in Java as in all object oriented programming languages.

How to squash commits in git after they have been pushed?

1) git rebase -i HEAD~4

To elaborate: It works on the current branch; the HEAD~4 means squashing the latest four commits; interactive mode (-i)

2) At this point, the editor opened, with the list of commits, to change the second and following commits, replacing pick with squash then save it.

output: Successfully rebased and updated refs/heads/branch-name.

3) git push origin refs/heads/branch-name --force

output:

remote:
remote: To create a merge request for branch-name, visit:
remote: http://xxx/sc/server/merge_requests/new?merge_request%5Bsource_branch%5D=sss
remote:To ip:sc/server.git
 + 84b4b60...5045693 branch-name -> branch-name (forced update)

Check if a time is between two times (time DataType)

This should also work (even in SQL-Server 2005):

SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
  AND Created <  DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))

DEMO

json_decode returns NULL after webservice call

I was having this problem, when I was calling a soap method to obtain my data, and then return a json string, when I tried to do json_decode I just keep getting null.

Since I was using nusoap to do the soap call I tried to just return json string and now I could do a json_decode, since I really neaded to get my data with a SOAP call, what I did was add ob_start() before include nusoap, id did my call genereate json string, and then before returning my json string I did ob_end_clean(), and GOT MY PROBLEM FIXED :)

EXAMPLE

//HRT - SIGNED
//20130116
//verifica se um num assoc deco é valido
ob_start();
require('/nusoap.php');
$aResponse['SimpleIsMemberResult']['IsMember'] = FALSE;
if(!empty($iNumAssociadoTmp))
{
    try
    {
        $client = new soapclientNusoap(PartnerService.svc?wsdl',
         array( 
            // OPTS 
            'trace' => 0,
            'exceptions' => false,
            'cache_wsdl' => WSDL_CACHE_NONE
         )
        );
    //MENSAGEM A ENVIAR
    $sMensagem1 = '
        <SimpleIsMember>
            <request>
                <CheckDigit>'.$iCheckDigitAssociado.'</CheckDigit>
                <Country>Portugal</Country>
                <MemberNumber">'.$iNumAssociadoDeco.'</MemberNumber>
            </request>
        </SimpleIsMember>';
    $aResponse = $client->call('SimpleIsMember',$sMensagem1);
    $aData = array('dados'=>$aResponse->xpto, 'success'=>$aResponse->example);
    }
}
ob_end_clean();
return json_encode($aData);