Programs & Examples On #Catransformlayer

CATransformLayer objects are used to create true 3D layer hierarchies, rather than the flattened hierarchy rendering model used by other CALayer classes.

How do I grant myself admin access to a local SQL Server instance?

Microsoft has an article about this issue. It goes through it all step by step.

https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/connect-to-sql-server-when-system-administrators-are-locked-out

In short it involves starting up the instance of sqlserver with -m like all the other answers suggest. However Microsoft provides slightly more detailed instructions.

From the Start page, start SQL Server Management Studio. On the View menu, select Registered Servers. (If your server is not already registered, right-click Local Server Groups, point to Tasks, and then click Register Local Servers.)

In the Registered Servers area, right-click your server, and then click SQL Server Configuration Manager. This should ask for permission to run as administrator, and then open the Configuration Manager program.

Close Management Studio.

In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, find your instance of SQL Server. (The default instance of SQL Server includes (MSSQLSERVER) after the computer name. Named instances appear in upper case with the same name that they have in Registered Servers.) Right-click the instance of SQL Server, and then click Properties.

On the Startup Parameters tab, in the Specify a startup parameter box, type -m and then click Add. (That's a dash then lower case letter m.)

Note

For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Be careful not to change any of the existing parameters. At the very end, add a new parameter ;-m and then click OK. (That's a semi-colon then a dash then lower case letter m.)

Click OK, and after the message to restart, right-click your server name, and then click Restart.

After SQL Server has restarted your server will be in single-user mode. Make sure that that SQL Server Agent is not running. If started, it will take your only connection.

On the Windows 8 start screen, right-click the icon for Management Studio. At the bottom of the screen, select Run as administrator. (This will pass your administrator credentials to SSMS.)

Note

For earlier versions of Windows, the Run as administrator option appears as a sub-menu.

In some configurations, SSMS will attempt to make several connections. Multiple connections will fail because SQL Server is in single-user mode. You can select one of the following actions to perform. Do one of the following.

a) Connect with Object Explorer using Windows Authentication (which includes your Administrator credentials). Expand Security, expand Logins, and double-click your own login. On the Server Roles page, select sysadmin, and then click OK.

b) Instead of connecting with Object Explorer, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). (You can only connect this way if you did not connect with Object Explorer.) Execute code such as the following to add a new Windows Authentication login that is a member of the sysadmin fixed server role. The following example adds a domain user named CONTOSO\PatK.

CREATE LOGIN [CONTOSO\PatK] FROM WINDOWS;   ALTER SERVER ROLE
sysadmin ADD MEMBER [CONTOSO\PatK];   

c) If your SQL Server is running in mixed authentication mode, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Execute code such as the following to create a new SQL Server Authentication login that is a member of the sysadmin fixed server role.

CREATE LOGIN TempLogin WITH PASSWORD = '************';   ALTER
SERVER ROLE sysadmin ADD MEMBER TempLogin;   

Warning:

Replace ************ with a strong password.

d) If your SQL Server is running in mixed authentication mode and you want to reset the password of the sa account, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Change the password of the sa account with the following syntax.

ALTER LOGIN sa WITH PASSWORD = '************';   Warning

Replace ************ with a strong password.

The following steps now change SQL Server back to multi-user mode. Close SSMS.

In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, right-click the instance of SQL Server, and then click Properties.

On the Startup Parameters tab, in the Existing parameters box, select -m and then click Remove.

Note

For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Remove the ;-m which you added earlier, and then click OK.

Right-click your server name, and then click Restart.

Now you should be able to connect normally with one of the accounts which is now a member of the sysadmin fixed server role.

Difference between socket and websocket?

Regarding your question (b), be aware that the Websocket specification hasn't been finalised. According to the W3C:

Implementors should be aware that this specification is not stable.

Personally I regard Websockets to be waaay too bleeding edge to use at present. Though I'll probably find them useful in a year or so.

jQuery: get parent, parent id?

 $(this).closest('ul').attr('id');

jQuery delete confirmation box

Try with this JSFiddle DEMO : http://jsfiddle.net/2yEtK/3/

Jquery Code:

$("a.removeRecord").live("click",function(event){
   event.stopPropagation();
   if(confirm("Do you want to delete?")) {
    this.click;
       alert("Ok");
   }
   else
   {
       alert("Cancel");
   }       
   event.preventDefault();

});

How to open warning/information/error dialog in Swing?

See How to Make Dialogs.

You can use:

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");

And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.

How should I print types like off_t and size_t?

To print off_t:

printf("%jd\n", (intmax_t)x);

To print size_t:

printf("%zu\n", x);

To print ssize_t:

printf("%zd\n", x);

See 7.19.6.1/7 in the C99 standard, or the more convenient POSIX documentation of formatting codes:

http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html

If your implementation doesn't support those formatting codes (for example because you're on C89), then you have a bit of a problem since AFAIK there aren't integer types in C89 that have formatting codes and are guaranteed to be as big as these types. So you need to do something implementation-specific.

For example if your compiler has long long and your standard library supports %lld, you can confidently expect that will serve in place of intmax_t. But if it doesn't, you'll have to fall back to long, which would fail on some other implementations because it's too small.

Matplotlib connect scatterplot points with line - Python

In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:

plt.plot(x,y,zorder=1) 
plt.scatter(x,y,zorder=2)

plots the scatter symbols on top of the line, while

plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)

plots the line over the scatter symbols.

See, e.g., the zorder demo

How to convert buffered image to image and vice-versa?

Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:

Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);     

BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);

bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);

Clear the form field after successful submission of php form

You can check this also

_x000D_
_x000D_
<form id="form1" method="post">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
    <option value="">Select One</option>
    <option value="FREE Account">FREE Account</option>
    <option value="Premium Account Monthly">Premium Account Monthly</option>
    <option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" ><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" ><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" ><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" ><br>
<label class="w">City :</label>
<input name="city" type="text" placeholder="City" required="required"><br>
<label class="w">Country :</label>
<select autofocus id="a1_txtBox1" name="country" required="required" placeholder="select one">
<option>Select One</option>
<option>UK</option>
<option>US</option>
</select>
<br>
<br>
<input type="reset" value="Submit" />

</form>
_x000D_
_x000D_
_x000D_

How to change the color of winform DataGridview header?

dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

Remove last 3 characters of string or number in javascript

Here is an approach using str.slice(0, -n). Where n is the number of characters you want to truncate.

_x000D_
_x000D_
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
_x000D_
_x000D_

Is there a way to specify how many characters of a string to print out using printf()?

Using printf you can do

printf("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");

If you're using C++, you can achieve the same result using the STL:

using namespace std; // for clarity
string s("A string that is more than 8 chars");
cout << "Here are the first 8 chars: ";
copy(s.begin(), s.begin() + 8, ostream_iterator<char>(cout));
cout << endl;

Or, less efficiently:

cout << "Here are the first 8 chars: " <<
        string(s.begin(), s.begin() + 8) << endl;

Capture key press without placing an input element on the page?

Code & detects ctrl+z

document.onkeyup = function(e) {
  if(e.ctrlKey && e.keyCode == 90) {
    // ctrl+z pressed
  }
}

About "*.d.ts" in TypeScript

I could not comment and thus am adding this as an answer.
We had some pain trying to map existing types to a javascript library.

To map a .d.ts file to its javascript file you need to give the .d.ts file the same name as the javascript file, keep them in the same folder, and point the code that needs it to the .d.ts file.

eg: test.js and test.d.ts are in the testdir/ folder, then you import it like this in a react component:

import * as Test from "./testdir/test";

The .d.ts file was exported as a namespace like this:

export as namespace Test;

export interface TestInterface1{}
export class TestClass1{}

How to loop over a Class attributes in Java?

While I agree with Jörn's answer if your class conforms to the JavaBeabs spec, here is a good alternative if it doesn't and you use Spring.

Spring has a class named ReflectionUtils that offers some very powerful functionality, including doWithFields(class, callback), a visitor-style method that lets you iterate over a classes fields using a callback object like this:

public void analyze(Object obj){
    ReflectionUtils.doWithFields(obj.getClass(), field -> {

        System.out.println("Field name: " + field.getName());
        field.setAccessible(true);
        System.out.println("Field value: "+ field.get(obj));

    });
}

But here's a warning: the class is labeled as "for internal use only", which is a pity if you ask me

Python datetime strptime() and strftime(): how to preserve the timezone information

Try this:

import pytz
import datetime

fmt = '%Y-%m-%d %H:%M:%S %Z'

d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = pytz.timezone('America/New_York').localize(d.strptime(d_string,fmt), is_dst=None)
print(d_string)
print(d2.strftime(fmt))

SQL User Defined Function Within Select

If it's a table-value function (returns a table set) you simply join it as a Table

this function generates one column table with all the values from passed comma-separated list

SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')

Python requests - print entire http request (raw)?

Note: this answer is outdated. Newer versions of requests support getting the request content directly, as AntonioHerraizS's answer documents.

It's not possible to get the true raw content of the request out of requests, since it only deals with higher level objects, such as headers and method type. requests uses urllib3 to send requests, but urllib3 also doesn't deal with raw data - it uses httplib. Here's a representative stack trace of a request:

-> r= requests.get("http://google.com")
  /usr/local/lib/python2.7/dist-packages/requests/api.py(55)get()
-> return request('get', url, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/api.py(44)request()
-> return session.request(method=method, url=url, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/sessions.py(382)request()
-> resp = self.send(prep, **send_kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/sessions.py(485)send()
-> r = adapter.send(request, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/adapters.py(324)send()
-> timeout=timeout
  /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(478)urlopen()
-> body=body, headers=headers)
  /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(285)_make_request()
-> conn.request(method, url, **httplib_request_kw)
  /usr/lib/python2.7/httplib.py(958)request()
-> self._send_request(method, url, body, headers)

Inside the httplib machinery, we can see HTTPConnection._send_request indirectly uses HTTPConnection._send_output, which finally creates the raw request and body (if it exists), and uses HTTPConnection.send to send them separately. send finally reaches the socket.

Since there's no hooks for doing what you want, as a last resort you can monkey patch httplib to get the content. It's a fragile solution, and you may need to adapt it if httplib is changed. If you intend to distribute software using this solution, you may want to consider packaging httplib instead of using the system's, which is easy, since it's a pure python module.

Alas, without further ado, the solution:

import requests
import httplib

def patch_send():
    old_send= httplib.HTTPConnection.send
    def new_send( self, data ):
        print data
        return old_send(self, data) #return is not necessary, but never hurts, in case the library is changed
    httplib.HTTPConnection.send= new_send

patch_send()
requests.get("http://www.python.org")

which yields the output:

GET / HTTP/1.1
Host: www.python.org
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/2.1.0 CPython/2.7.3 Linux/3.2.0-23-generic-pae

Most efficient way to find smallest of 3 numbers Java?

I would use min/max (and not worry otherwise) ... however, here is another "long hand" approach which may or may not be easier for some people to understand. (I would not expect it to be faster or slower than the code in the post.)

int smallest;
if (a < b) {
  if (a > c) {
    smallest = c;
  } else { // a <= c
    smallest = a;
  }
} else { // a >= b
  if (b > c) {
    smallest = c;
  } else { // b <= c
    smallest = b;
  }
}

Just throwing it into the mix.

Note that this is just the side-effecting variant of Abhishek's answer.

Format Instant to String

Time Zone

To format an Instant a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.

The time-zone can be added directly to the formatter using withZone().

DateTimeFormatter formatter =
    DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                     .withLocale( Locale.UK )
                     .withZone( ZoneId.systemDefault() );

If you specifically want an ISO-8601 format with no explicit time-zone (as the OP asked), with the time-zone implicitly UTC, you need

DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))

Generating String

Now use that formatter to generate the String representation of your Instant.

Instant instant = Instant.now();
String output = formatter.format( instant );

Dump to console.

System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );

When run.

formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34

How do I resolve a HTTP 414 "Request URI too long" error?

Under Apache, the limit is a configurable value, LimitRequestLine. Change this value to something larger than its default of 8190 if you want to support a longer request URI. The value is in /etc/apache2/apache2.conf. If not, add a new line (LimitRequestLine 10000) under AccessFileName .htaccess.

However, note that if you're actually running into this limit, you are probably abusing GET to begin with. You should use POST to transmit this sort of data -- especially since you even concede that you're using it to update values. If you check the link above, you'll notice that Apache even says "Under normal conditions, the value should not be changed from the default."

Get size of folder or file

If you want to use Java 8 NIO API, the following program will print the size, in bytes, of the directory it is located in.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathSize {

    public static void main(String[] args) {
        Path path = Paths.get(".");
        long size = calculateSize(path);
        System.out.println(size);
    }

    /**
     * Returns the size, in bytes, of the specified <tt>path</tt>. If the given
     * path is a regular file, trivially its size is returned. Else the path is
     * a directory and its contents are recursively explored, returning the
     * total sum of all files within the directory.
     * <p>
     * If an I/O exception occurs, it is suppressed within this method and
     * <tt>0</tt> is returned as the size of the specified <tt>path</tt>.
     * 
     * @param path path whose size is to be returned
     * @return size of the specified path
     */
    public static long calculateSize(Path path) {
        try {
            if (Files.isRegularFile(path)) {
                return Files.size(path);
            }

            return Files.list(path).mapToLong(PathSize::calculateSize).sum();
        } catch (IOException e) {
            return 0L;
        }
    }

}

The calculateSize method is universal for Path objects, so it also works for files. Note that if a file or directory is inaccessible, in this case the returned size of the path object will be 0.

How do I break out of a loop in Perl?

Additional data (in case you have more questions):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------

How do I print a double value without scientific notation using Java?

For integer values represented by a double, you can use this code, which is much faster than the other solutions.

public static String doubleToString(final double d) {
    // check for integer, also see https://stackoverflow.com/a/9898613/868941 and
    // https://github.com/google/guava/blob/master/guava/src/com/google/common/math/DoubleMath.java
    if (isMathematicalInteger(d)) {
        return Long.toString((long)d);
    } else {
        // or use any of the solutions provided by others, this is the best
        DecimalFormat df = 
            new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
        df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
        return df.format(d);
    }
}

// Java 8+
public static boolean isMathematicalInteger(final double d) {
    return StrictMath.rint(d) == d && Double.isFinite(d);
}

How to get name of the computer in VBA?

Dim sHostName As String

' Get Host Name / Get Computer Name

sHostName = Environ$("computername")

jQuery Call to WebService returns "No Transport" error

If your jQuery page isn't being loaded from http://localhost:54473 then this issue is probably because you're trying to make cross-domain request.

Update 1 Take a look at this blog post.

Update 2 If this is indeed the problem (and I suspect it is), you might want to check out JSONP as a solution. Here are a few links that might help you get started:

Java Does Not Equal (!=) Not Working?

Please use !statusCheck.equals("success") instead of !=.

Here are more details.

How can I compare two ordered lists in python?

The expression a == b should do the job.

Drawing Circle with OpenGL

It looks like immediately after you draw the circle, you go into the main glut loop, where you've set the Draw() function to draw every time through the loop. So it's probably drawing the circle, then erasing it immediately and drawing the square. You should probably either make DrawCircle() your glutDisplayFunc(), or call DrawCircle() from Draw().

MultipartException: Current request is not a multipart request

I was also facing the same issue with Postman for multipart. I fixed it by doing the following steps:

  • Do not select Content-Type in the Headers section.
  • In Body tab of Postman you should select form-data and select file type.

It worked for me.

How to get data from database in javascript based on the value passed to the function

The error is coming as your query is getting formed as

SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.

What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as

SELECT * FROM Employ where number = temp;

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

First create table without auto_increment,

CREATE TABLE `members`(
    `id` int(11) NOT NULL,
    `memberid` VARCHAR( 30 ) NOT NULL ,
    `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    `firstname` VARCHAR( 50 ) NULL ,
    `lastname` VARCHAR( 50 ) NULL
    PRIMARY KEY (memberid) 
) ENGINE = MYISAM;

after set id as index,

ALTER TABLE `members` ADD INDEX(`id`);

after set id as auto_increment,

ALTER TABLE `members` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;

Or

CREATE TABLE IF NOT EXISTS `members` (
    `id` int(11) NOT NULL,
    `memberid` VARCHAR( 30 ) NOT NULL ,
    `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    `firstname` VARCHAR( 50 ) NULL ,
    `lastname` VARCHAR( 50 ) NULL,
      PRIMARY KEY (`memberid`),
      KEY `id` (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

How to dismiss keyboard for UITextView with return key?

Swift Code

Implement UITextViewDelegate in your class / View like so:

class MyClass: UITextViewDelegate  { ...

set the textView delegate to self

myTextView.delegate = self

And then implement the following:

  func textViewDidChange(_ textView: UITextView) {
    if textView.text.characters.count >= 1 {

        if let lastChar = textView.text.characters.last {

            if(lastChar == "\n"){

              textView.text = textView.text.substring(to: textView.text.index(before: textView.text.endIndex))
              textView.resignFirstResponder()
            }
        }
    }
}

EDIT I updated the code because it is never a good idea to change the user input in a textfield to for a workarround and not resetting the state after the hack code completed.

Display/Print one column from a DataFrame of Series in Pandas

Not sure what you are really after but if you want to print exactly what you have you can do:

Option 1

print(df['Item'].to_csv(index=False))

Sweet
Candy
Chocolate

Option 2

for v in df['Item']:
    print(v)

Sweet
Candy
Chocolate

How do I change the color of radio buttons?

A radio button is a native element specific to each OS/browser. There is no way to change its color/style, unless you want to implement custom images or use a custom Javascript library which includes images (e.g. this - cached link)

Android ListView Text Color

never use getApplicationContext(). Just use your Activity as the Context. See if that helps.

Please check here: CommonsWare answers

Android - Handle "Enter" in an EditText

This should work

input.addTextChangedListener(new TextWatcher() {

           @Override
           public void afterTextChanged(Editable s) {}

           @Override    
           public void beforeTextChanged(CharSequence s, int start,
             int count, int after) {
           }

           @Override    
           public void onTextChanged(CharSequence s, int start,
             int before, int count) {
               if( -1 != input.getText().toString().indexOf( "\n" ) ){
                   input.setText("Enter was pressed!");
                    }
           }
          });

What is the best way to conditionally apply attributes in AngularJS?

Regarding the accepted solution, the one posted by Ashley Davis, the method described still prints the attribute in the DOM, regardless of the fact that the value it has been assigned is undefined.

For example, on an input field setup with both an ng-model and a value attribute:

<input type="text" name="myInput" data-ng-attr-value="{{myValue}}" data-ng-model="myModel" />

Regardless of what's behind myValue, the value attribute still gets printed in the DOM, thus, interpreted. Ng-model then, becomes overridden.

A bit unpleasant, but using ng-if does the trick:

<input type="text" name="myInput" data-ng-if="value" data-ng-attr-value="{{myValue}}" data-ng-model="myModel" />
<input type="text" name="myInput" data-ng-if="!value" data-ng-model="myModel" />

I would recommend using a more detailed check inside the ng-if directives :)

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

OPTION 1: UNICODE COLUMN SORT ARROWS

I found this one very handy for a single character column sorter. (Looks good upscaled).

&#x21D5; = ?

Unicode table column sort arrows

IMPORTANT NOTE (When using Unicode symbols)

Unicode support varies dependant on the symbol of choice, browser and the font family. If you find your chosen symbol does not work in some browsers then try using a different font-family. Microsoft recommends "Segoe UI Symbol" however it would be wise to include the font with your website as not many people have it on their computers.

Open this page in other browsers to see which symbols render with the default font.


Some more Unicode arrows.

You can copy them right off the page below or you can use the code.

Each row of arrows is numbered from left to right:

0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

Simply insert the corresponding number/letter before the closing semi-colon as above.


&#x219;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21A;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21B;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21C;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21D;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21E;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21F;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


Additional HTML unicode symbols

A selected list of other helpful Unicode icons/symbols.

U+2302  ¦   HOUSE
U+2303  ^   UP ARROWHEAD
U+2304  ?   DOWN ARROWHEAD
U+2305  ?   PROJECTIVE
U+2306  ?   PERSPECTIVE
U+2307  ?   WAVY LINE
U+2315  ?   TELEPHONE RECORDER
U+2316  ?   POSITION INDICATOR
U+2317  ?   VIEWDATA SQUARE
U+2318  ?   PLACE OF INTEREST SIGN
U+231A  ?   WATCH
U+231B  ?   HOURGLASS
U+2326  ?   ERASE TO THE RIGHT
U+2327  ?   X IN A RECTANGLE BOX
U+2328  ?   KEYBOARD
U+2329  <   LEFT-POINTING ANGLE BRACKET
U+232A  >   RIGHT-POINTING ANGLE BRACKET
U+232B  ?   ERASE TO THE LEFT
U+23E9  ?   BLACK RIGHT-POINTING DOUBLE TRIANGLE
U+23EA  ?   BLACK LEFT-POINTING DOUBLE TRIANGLE
U+23EB  ?   BLACK UP-POINTING DOUBLE TRIANGLE
U+23EC  ?   BLACK DOWN-POINTING DOUBLE TRIANGLE
U+23ED  ?   BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR
U+23EE  ?   BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR
U+23EF  ?   BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR
U+23F0  ?   ALARM CLOCK
U+23F1  ?   STOPWATCH
U+23F2  ?   TIMER CLOCK
U+23F3  ?   HOURGLASS WITH FLOWING SAND
U+2600  ?   BLACK SUN WITH RAYS
U+2601  ?   CLOUD
U+2602  ?   UMBRELLA
U+2603  ?   SNOWMAN
U+2604  ?   COMET
U+2605  ?   BLACK STAR
U+2606  ?   WHITE STAR
U+2607  ?   LIGHTNING
U+2608  ?   THUNDERSTORM
U+2609  ?   SUN
U+260A  ?   ASCENDING NODE
U+260B  ?   DESCENDING NODE
U+260C  ?   CONJUNCTION
U+260D  ?   OPPOSITION
U+260E  ?   BLACK TELEPHONE
U+260F  ?   WHITE TELEPHONE
U+2610  ?   BALLOT BOX
U+2611  ?   BALLOT BOX WITH CHECK
U+2612  ?   BALLOT BOX WITH X
U+2613  ?   SALTIRE
U+2614  ?   UMBRELLA WITH RAINDROPS
U+2615  ?   HOT BEVERAGE
U+2616  ?   WHITE SHOGI PIECE
U+2617  ?   BLACK SHOGI PIECE
U+2618  ?   SHAMROCK
U+2619  ?   REVERSED ROTATED FLORAL HEART BULLET
U+261A  ?   BLACK LEFT-POINTING INDEX
U+261B  ?   BLACK RIGHT-POINTING INDEX
U+261C  ?   WHITE LEFT POINTING INDEX
U+261D  ?   WHITE UP POINTING INDEX
U+261E  ?   WHITE RIGHT POINTING INDEX
U+261F  ?   WHITE DOWN POINTING INDEX
U+2620  ?   SKULL AND CROSSBONES
U+2621  ?   CAUTION SIGN
U+2622  ?   RADIOACTIVE SIGN
U+2623  ?   BIOHAZARD SIGN
U+262A  ?   STAR AND CRESCENT
U+262B  ?   FARSI SYMBOL
U+262C  ?   ADI SHAKTI
U+262D  ?   HAMMER AND SICKLE
U+262E  ?   PEACE SYMBOL
U+262F  ?   YIN YANG
U+2638  ?   WHEEL OF DHARMA
U+2639  ?   WHITE FROWNING FACE
U+263A  ?   WHITE SMILING FACE
U+263B  ?   BLACK SMILING FACE
U+263C  ¤   WHITE SUN WITH RAYS
U+263D  ?   FIRST QUARTER MOON
U+263E  ?   LAST QUARTER MOON
U+263F  ?   MERCURY
U+2640  ?   FEMALE SIGN
U+2641  ?   EARTH
U+2642  ?   MALE SIGN
U+2643  ?   JUPITER
U+2644  ?   SATURN
U+2645  ?   URANUS
U+2646  ?   NEPTUNE
U+2647  ?   PLUTO
U+2648  ?   ARIES
U+2649  ?   TAURUS
U+264A  ?   GEMINI
U+264B  ?   CANCER
U+264C  ?   LEO
U+264D  ?   VIRGO
U+264E  ?   LIBRA
U+264F  ?   SCORPIUS
U+2650  ?   SAGITTARIUS
U+2651  ?   CAPRICORN
U+2652  ?   AQUARIUS
U+2653  ?   PISCES
U+2654  ?   WHITE CHESS KING
U+2655  ?   WHITE CHESS QUEEN
U+2656  ?   WHITE CHESS ROOK
U+2657  ?   WHITE CHESS BISHOP
U+2658  ?   WHITE CHESS KNIGHT
U+2659  ?   WHITE CHESS PAWN
U+265A  ?   BLACK CHESS KING
U+265B  ?   BLACK CHESS QUEEN
U+265C  ?   BLACK CHESS ROOK
U+265D  ?   BLACK CHESS BISHOP
U+265E  ?   BLACK CHESS KNIGHT
U+265F  ?   BLACK CHESS PAWN
U+2660  ?   BLACK SPADE SUIT
U+2661  ?   WHITE HEART SUIT
U+2662  ?   WHITE DIAMOND SUIT
U+2663  ?   BLACK CLUB SUITE
U+2664  ?   WHITE SPADE SUIT
U+2665  ?   BLACK HEART SUIT
U+2666  ?   BLACK DIAMOND SUIT
U+2667  ?   WHITE CLUB SUITE
U+2668  ?   HOT SPRINGS
U+2669  ?   QUARTER NOTE
U+266A  ?   EIGHTH NOTE
U+266B  ?   BEAMED EIGHTH NOTES
U+266C  ?   BEAMED SIXTEENTH NOTES
U+266D  ?   MUSIC FLAT SIGN
U+266E  ?   MUSIC NATURAL SIGN
U+266F  ?   MUSIC SHARP SIGN
U+267A  ?   RECYCLING SYMBOL FOR GENERIC MATERIALS
U+267B  ?   BLACK UNIVERSAL RECYCLING SYMBOL
U+267C  ?   RECYCLED PAPER SYMBOL
U+267D  ?   PARTIALLY-RECYCLED PAPER SYMBOL
U+267E  ?   PERMANENT PAPER SIGN
U+267F  ?   WHEELCHAIR SYMBOL
U+2680  ?   DIE FACE-1
U+2681  ?   DIE FACE-2
U+2682  ?   DIE FACE-3
U+2683  ?   DIE FACE-4
U+2684  ?   DIE FACE-5
U+2685  ?   DIE FACE-6
U+2686  ?   WHITE CIRCLE WITH DOT RIGHT
U+2687  ?   WHITE CIRCLE WITH TWO DOTS
U+2688  ?   BLACK CIRCLE WITH WHITE DOT RIGHT
U+2689  ?   BLACK CIRCLE WITH TWO WHITE DOTS
U+268A  ?   MONOGRAM FOR YANG
U+268B  ?   MONOGRAM FOR YIN
U+268C  ?   DIGRAM FOR GREATER YANG
U+268D  ?   DIGRAM FOR LESSER YIN
U+268E  ?   DIGRAM FOR LESSER YANG
U+268F  ?   DIGRAM FOR GREATER YIN
U+2690  ?   WHITE FLAG
U+2691  ?   BLACK FLAG
U+2692  ?   HAMMER AND PICK
U+2693  ?   ANCHOR
U+2694  ?   CROSSED SWORDS
U+2695  ?   STAFF OF AESCULAPIUS
U+2696  ?   SCALES
U+2697  ?   ALEMBIC
U+2698  ?   FLOWER
U+2699  ?   GEAR
U+269A  ?   STAFF OF HERMES
U+269B  ?   ATOM SYMBOL
U+269C  ?   FLEUR-DE-LIS
U+269D  ?   OUTLINED WHITE STAR
U+269E  ?   THREE LINES CONVERGING RIGHT
U+269F  ?   THREE LINES CONVERGING LEFT
U+26A0  ?   WARNING SIGN
U+26A1  ?   HIGH VOLTAGE SIGN
U+26A2  ?   DOUBLED FEMALE SIGN
U+26A3  ?   DOUBLED MALE SIGN
U+26A4  ?   INTERLOCKED FEMALE AND MALE SIGN
U+26A5  ?   MALE AND FEMALE SIGN
U+26A6  ?   MALE WITH STROKE SIGN
U+26A7  ?   MALE WITH STROKE AND MALE AND FEMALE SIGN
U+26A8  ?   VERTICAL MALE WITH STROKE SIGN
U+26A9  ?   HORIZONTAL MALE WITH STROKE SIGN
U+26AA  ?   MEDIUM WHITE CIRCLE
U+26AB  ?   MEDIUM BLACK CIRCLE
U+26BD  ?   SOCCER BALL
U+26BE  ?   BASEBALL
U+26BF  ?   SQUARED KEY
U+26C0  ?   WHITE DRAUGHTSMAN
U+26C1  ?   WHITE DRAUGHTS KING
U+26C2  ?   BLACK DRAUGHTSMAN
U+26C3  ?   BLACK DRAUGHTS KING
U+26C4  ?   SNOWMAN WITHOUT SNOW
U+26C5  ?   SUN BEHIND CLOUD
U+26C6  ?   RAIN
U+26C7  ?   BLACK SNOWMAN
U+26C8  ?   THUNDER CLOUD AND RAIN
U+26C9  ?   TURNED WHITE SHOGI PIECE
U+26CA  ?   TURNED BLACK SHOGI PIECE
U+26CB  ?   WHITE DIAMOND IN SQUARE
U+26CC  ?   CROSSING LANES
U+26CD  ?   DISABLED CAR
U+26CE  ?   OPHIUCHUS
U+26CF  ?   PICK
U+26D0  ?   CAR SLIDING
U+26D1  ?   HELMET WITH WHITE CROSS
U+26D2  ?   CIRCLED CROSSING LANES
U+26D3  ?   CHAINS
U+26D4  ?   NO ENTRY
U+26D5  ?   ALTERNATE ONE-WAY LEFT WAY TRAFFIC
U+26D6  ?   BLACK TWO-WAY LEFT WAY TRAFFIC
U+26D7  ?   WHITE TWO-WAY LEFT WAY TRAFFIC
U+26D8  ?   BLACK LEFT LANE MERGE
U+26D9  ?   WHITE LEFT LANE MERGE
U+26DA  ?   DRIVE SLOW SIGN
U+26DB  ?   HEAVY WHITE DOWN-POINTING TRIANGLE
U+26DC  ?   LEFT CLOSED ENTRY
U+26DD  ?   SQUARED SALTIRE
U+26DE  ?   FALLING DIAGONAL IN WHITE CIRCLE IN BLACK SQUARE
U+26DF  ?   BLACK TRUCK
U+26E0  ?   RESTRICTED LEFT ENTRY-1
U+26E1  ?   RESTRICTED LEFT ENTRY-2
U+26E2  ?   ASTRONOMICAL SYMBOL FOR URANUS
U+26E3  ?   HEAVY CIRCLE WITH STROKE AND TWO DOTS ABOVE
U+26E4  ?   PENTAGRAM
U+26E5  ?   RIGHT-HANDED INTERLACED PENTAGRAM
U+26E6  ?   LEFT-HANDED INTERLACED PENTAGRAM
U+26E7  ?   INVERTED PENTAGRAM
U+26E8  ?   BLACK CROSS ON SHIELD
U+26E9  ?   SHINTO SHRINE
U+26EA  ?   CHURCH
U+26EB  ?   CASTLE
U+26EC  ?   HISTORIC SITE
U+26ED  ?   GEAR WITHOUT HUB
U+26EE  ?   GEAR WITH HANDLES
U+26EF  ?   MAP SYMBOL FOR LIGHTHOUSE
U+26F0  ?   MOUNTAIN
U+26F1  ?   UMBRELLA ON GROUND
U+26F2  ?   FOUNTAIN
U+26F3  ?   FLAG IN HOLE
U+26F4  ?   FERRY
U+26F5  ?   SAILBOAT
U+26F6  ?   SQUARE FOUR CORNERS
U+26F7  ?   SKIER
U+26F8  ?   ICE SKATE
U+26F9  ?   PERSON WITH BALL
U+26FA  ?   TENT
U+26FD  ?   FUEL PUMP
U+26FE  ?   CUP ON BLACK SQUARE
U+26FF  ?   WHITE FLAG WITH HORIZONTAL MIDDLE BLACK STRIPE
U+2701  ?   UPPER BLADE SCISSORS
U+2702  ?   BLACK SCISSORS
U+2703  ?   LOWER BLADE SCISSORS
U+2704  ?   WHITE SCISSORS
U+2705  ?   WHITE HEAVY CHECK MARK
U+2706  ?   TELEPHONE LOCATION SIGN
U+2707  ?   TAPE DRIVE
U+2708  ?   AIRPLANE
U+2709  ?   ENVELOPE
U+270A  ?   RAISED FIST
U+270B  ?   RAISED HAND
U+270C  ?   VICTORY HAND
U+270D  ?   WRITING HAND
U+270E  ?   LOWER RIGHT PENCIL
U+270F  ?   PENCIL
U+2710  ?   UPPER RIGHT PENCIL
U+2711  ?   WHITE NIB
U+2712  ?   BLACK NIB
U+2713  ?   CHECK MARK
U+2714  ?   HEAVY CHECK MARK
U+2715  ?   MULTIPLICATION X
U+2716  ?   HEAVY MULTIPLICATION X
U+2717  ?   BALLOT X
U+2718  ?   HEAVY BALLOT X
U+2719  ?   OUTLINED GREEK CROSS
U+271A  ?   HEAVY GREEK CROSS
U+271B  ?   OPEN CENTRE CROSS
U+271C  ?   HEAVY OPEN CENTRE CROSS
U+271D  ?   LATIN CROSS
U+271E  ?   SHADOWED WHITE LATIN CROSS
U+271F  ?   OUTLINED LATIN CROSS
U+2720  ?   MALTESE CROSS
U+2721  ?   STAR OF DAVID
U+2722  ?   FOUR TEARDROP-SPOKED ASTERISK
U+2723  ?   FOUR BALLOON-SPOKED ASTERISK
U+2724  ?   HEAVY FOUR BALLOON-SPOKED ASTERISK
U+2725  ?   FOUR CLUB-SPOKED ASTERISK
U+2726  ?   BLACK FOUR POINTED STAR
U+2727  ?   WHITE FOUR POINTED STAR
U+2728  ?   SPARKLES
U+2729  ?   STRESS OUTLINED WHITE STAR
U+272A  ?   CIRCLED WHITE STAR
U+272B  ?   OPEN CENTRE BLACK STAR
U+272C  ?   BLACK CENTRE WHITE STAR
U+272D  ?   OUTLINED BLACK STAR
U+272E  ?   HEAVY OUTLINED BLACK STAR
U+272F  ?   PINWHEEL STAR
U+2730  ?   SHADOWED WHITE STAR
U+2731  ?   HEAVY ASTERISK
U+2732  ?   OPEN CENTRE ASTERISK
U+2733  ?   EIGHT SPOKED ASTERISK
U+2734  ?   EIGHT POINTED BLACK STAR
U+2735  ?   EIGHT POINTED PINWHEEL STAR
U+2736  ?   SIX POINTED BLACK STAR
U+2737  ?   EIGHT POINTED RECTILINEAR BLACK STAR
U+2738  ?   HEAVY EIGHT POINTED RECTILINEAR BLACK STAR
U+2739  ?   TWELVE POINTED BLACK STAR
U+273A  ?   SIXTEEN POINTED ASTERISK
U+273B  ?   TEARDROP-SPOKED ASTERISK
U+273C  ?   OPEN CENTRE TEARDROP-SPOKED ASTERISK
U+273D  ?   HEAVY TEARDROP-SPOKED ASTERISK
U+273E  ?   SIX PETALLED BLACK AND WHITE FLORETTE
U+273F  ?   BLACK FLORETTE
U+2740  ?   WHITE FLORETTE
U+2741  ?   EIGHT PETALLED OUTLINED BLACK FLORETTE
U+2742  ?   CIRCLED OPEN CENTRE EIGHT POINTED STAR
U+2743  ?   HEAVY TEARDROP-SPOKED PINWHEEL ASTERISK
U+2744  ?   SNOWFLAKE
U+2745  ?   TIGHT TRIFOLIATE SNOWFLAKE
U+2746  ?   HEAVY CHEVRON SNOWFLAKE
U+2747  ?   SPARKLE
U+2748  ?   HEAVY SPARKLE
U+2749  ?   BALLOON-SPOKED ASTERISK
U+274A  ?   EIGHT TEARDROP-SPOKED PROPELLER ASTERISK
U+274B  ?   HEAVY EIGHT TEARDROP-SPOKED PROPELLER ASTERISK
U+274C  ?   CROSS MARK
U+274D  ?   SHADOWED WHITE CIRCLE
U+274E  ?   NEGATIVE SQUARED CROSS MARK
U+2753  ?   BLACK QUESTION MARK ORNAMENT
U+2754  ?   WHITE QUESTION MARK ORNAMENT
U+2755  ?   WHITE EXCLAMATION MARK ORNAMENT
U+2756  ?   BLACK DIAMOND MINUS WHITE X
U+2757  ?   HEAVY EXCLAMATION MARK SYMBOL
U+275B  ?   HEAVY SINGLE TURNED COMMA QUOTATION MARK ORNAMENT
U+275C  ?   HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT
U+275D  ?   HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT
U+275E  ?   HEAVY DOUBLE COMMA QUOTATION MARK ORNAMENT
U+275F  ?   HEAVY LOW SINGLE COMMA QUOTATION MARK ORNAMENT
U+2760  ?   HEAVY LOW DOUBLE COMMA QUOTATION MARK ORNAMENT
U+2761  ?   CURVED STEM PARAGRAPH SIGN ORNAMENT
U+2762  ?   HEAVY EXCLAMATION MARK ORNAMENT
U+2763  ?   HEAVY HEART EXCLAMATION MARK ORNAMENT
U+2764  ?   HEAVY BLACK HEART
U+2765  ?   ROTATED HEAVY BLACK HEART BULLET
U+2766  ?   FLORAL HEART
U+2767  ?   ROTATED FLORAL HEART BULLET
U+276C  ?   MEDIUM LEFT-POINTING ANGLE BRACKET ORNAMENT
U+276D  ?   MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT
U+276E  ?   HEAVY LEFT-POINTING ANGLE QUOTATION MARK ORNAMENT
U+276F  ?   HEAVY RIGHT-POINTING ANGLE QUOTATION MARK ORNAMENT
U+2770  ?   HEAVY LEFT-POINTING ANGLE BRACKET ORNAMENT
U+2771  ?   HEAVY RIGHT-POINTING ANGLE BRACKET ORNAMENT
U+2794  ?   HEAVY WIDE-HEADED RIGHTWARDS ARROW
U+2795  ?   HEAVY PLUS SIGN
U+2796  ?   HEAVY MINUS SIGN
U+2797  ?   HEAVY DIVISION SIGN
U+2798  ?   HEAVY SOUTH EAST ARROW
U+2799  ?   HEAVY RIGHTWARDS ARROW
U+279A  ?   HEAVY NORTH EAST ARROW
U+279B  ?   DRAFTING POINT RIGHTWARDS ARROW
U+279C  ?   HEAVY ROUND-TIPPED RIGHTWARDS ARROW
U+279D  ?   TRIANGLE-HEADED RIGHTWARDS ARROW
U+279E  ?   HEAVY TRIANGLE-HEADED RIGHTWARDS ARROW
U+279F  ?   DASHED TRIANGLE-HEADED RIGHTWARDS ARROW
U+27A0  ?   HEAVY DASHED TRIANGLE-HEADED RIGHTWARDS ARROW
U+27A1  ?   BLACK RIGHTWARDS ARROW
U+27A2  ?   THREE-D TOP-LIGHTED RIGHTWARDS ARROWHEAD
U+27A3  ?   THREE-D BOTTOM-LIGHTED RIGHTWARDS ARROWHEAD
U+27A4  ?   BLACK RIGHTWARDS ARROWHEAD
U+27A5  ?   HEAVY BLACK CURVED DOWNWARDS AND RIGHTWARDS ARROW
U+27A6  ?   HEAVY BLACK CURVED UPWARDS AND RIGHTWARDS ARROW
U+27A7  ?   SQUAT BLACK RIGHTWARDS ARROW
U+27A8  ?   HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW
U+27A9  ?   RIGHT-SHADED WHITE RIGHTWARDS ARROW
U+27AA  ?   LEFT-SHADED WHITE RIGHTWARDS ARROW
U+27AB  ?   BACK-TILTED SHADOWED WHITE RIGHTWARDS ARROW
U+27AC  ?   FRONT-TILTED SHADOWED WHITE RIGHTWARDS ARROW
U+27AD  ?   HEAVY LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27AE  ?   HEAVY UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27AF  ?   NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27B0  ?   CURLY LOOP
U+27B1  ?   NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27B2  ?   CIRCLED HEAVY WHITE RIGHTWARDS ARROW
U+27B3  ?   WHITE-FEATHERED RIGHTWARDS ARROW
U+27B4  ?   BLACK-FEATHERED SOUTH EAST ARROW
U+27B5  ?   BLACK-FEATHERED RIGHTWARDS ARROW
U+27B6  ?   BLACK-FEATHERED NORTH EAST ARROW
U+27B7  ?   HEAVY BLACK-FEATHERED SOUTH EAST ARROW
U+27B8  ?   HEAVY BLACK-FEATHERED RIGHTWARDS ARROW
U+27B9  ?   HEAVY BLACK-FEATHERED NORTH EAST ARROW
U+27BA  ?   TEARDROP-BARBED RIGHTWARDS ARROW
U+27BB  ?   HEAVY TEARDROP-SHANKED RIGHTWARDS ARROW
U+27BC  ?   WEDGE-TAILED RIGHTWARDS ARROW
U+27BD  ?   HEAVY WEDGE-TAILED RIGHTWARDS ARROW
U+27BE  ?   OPEN-OUTLINED RIGHTWARDS ARROW
U+27C0  ?   THREE DIMENSIONAL ANGLE
U+27E8  ?   MATHEMATICAL LEFT ANGLE BRACKET
U+27E9  ?   MATHEMATICAL RIGHT ANGLE BRACKET
U+27EA  ?   MATHEMATICAL LEFT DOUBLE ANGLE BRACKET
U+27EB  ?   MATHEMATICAL RIGHT DOUBLE ANGLE BRACKET
U+27F0  ?   UPWARDS QUADRUPLE ARROW
U+27F1  ?   DOWNWARDS QUADRUPLE ARROW
U+27F2  ?   ANTICLOCKWISE GAPPED CIRCLE ARROW
U+27F3  ?   CLOCKWISE GAPPED CIRCLE ARROW
U+27F4  ?   RIGHT ARROW WITH CIRCLED PLUS
U+27F5  ?   LONG LEFTWARDS ARROW
U+27F6  ?   LONG RIGHTWARDS ARROW
U+27F7  ?   LONG LEFT RIGHT ARROW
U+27F8  ?   LONG LEFTWARDS DOUBLE ARROW
U+27F9  ?   LONG RIGHTWARDS DOUBLE ARROW
U+27FA  ?   LONG LEFT RIGHT DOUBLE ARROW
U+27FB  ?   LONG LEFTWARDS ARROW FROM BAR
U+27FC  ?   LONG RIGHTWARDS ARROW FROM BAR
U+27FD  ?   LONG LEFTWARDS DOUBLE ARROW FROM BAR
U+27FE  ?   LONG RIGHTWARDS DOUBLE ARROW FROM BAR
U+27FF  ?   LONG RIGHTWARDS SQUIGGLE ARROW
U+2900  ?   RIGHTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE
U+2901  ?   RIGHTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE
U+2902  ?   LEFTWARDS DOUBLE ARROW WITH VERTICAL STROKE
U+2903  ?   RIGHTWARDS DOUBLE ARROW WITH VERTICAL STROKE
U+2904  ?   LEFT RIGHT DOUBLE ARROW WITH VERTICAL STROKE
U+2905  ?   RIGHTWARDS TWO-HEADED ARROW FROM BAR
U+2906  ?   LEFTWARDS DOUBLE ARROW FROM BAR
U+2907  ?   RIGHTWARDS DOUBLE ARROW FROM BAR
U+2908  ?   DOWNWARDS ARROW WITH HORIZONTAL STROKE
U+2909  ?   UPWARDS ARROW WITH HORIZONTAL STROKE
U+290A  ?   UPWARDS TRIPLE ARROW
U+290B  ?   DOWNWARDS TRIPLE ARROW
U+290C  ?   LEFTWARDS DOUBLE DASH ARROW
U+290D  ?   RIGHTWARDS DOUBLE DASH ARROW
U+290E  ?   LEFTWARDS TRIPLE DASH ARROW
U+290F  ?   RIGHTWARDS TRIPLE DASH ARROW
U+2910  ?   RIGHTWARDS TWO-HEADED TRIPLE DASH ARROW
U+2911  ?   RIGHTWARDS ARROW WITH DOTTED STEM
U+2912  ?   UPWARDS ARROW TO BAR
U+2913  ?   DOWNWARDS ARROW TO BAR
U+2914  ?   RIGHTWARDS ARROW WITH TAIL WITH VERTICAL STROKE
U+2915  ?   RIGHTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2916  ?   RIGHTWARDS TWO-HEADED ARROW WITH TAIL
U+2917  ?   RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE
U+2918  ?   RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2919  ?   LEFTWARDS ARROW-TAIL
U+291A  ?   RIGHTWARDS ARROW-TAIL
U+291B  ?   LEFTWARDS DOUBLE ARROW-TAIL
U+291C  ?   RIGHTWARDS DOUBLE ARROW-TAIL
U+291D  ?   LEFTWARDS ARROW TO BLACK DIAMOND
U+291E  ?   RIGHTWARDS ARROW TO BLACK DIAMOND
U+291F  ?   LEFTWARDS ARROW FROM BAR TO BLACK DIAMOND
U+2920  ?   RIGHTWARDS ARROW FROM BAR TO BLACK DIAMOND
U+2921  ?   NORTHWEST AND SOUTH EAST ARROW
U+2922  ?   NORTHEAST AND SOUTH WEST ARROW
U+2923  ?   NORTH WEST ARROW WITH HOOK
U+2924  ?   NORTH EAST ARROW WITH HOOK
U+2925  ?   SOUTH EAST ARROW WITH HOOK
U+2926  ?   SOUTH WEST ARROW WITH HOOK
U+2927  ?   NORTH WEST ARROW AND NORTH EAST ARROW
U+2928  ?   NORTH EAST ARROW AND SOUTH EAST ARROW
U+2929  ?   SOUTH EAST ARROW AND SOUTH WEST ARROW
U+292A  ?   SOUTH WEST ARROW AND NORTH WEST ARROW
U+292B  ?   RISING DIAGONAL CROSSING FALLING DIAGONAL
U+292C  ?   FALLING DIAGONAL CROSSING RISING DIAGONAL
U+292D  ?   SOUTH EAST ARROW CROSSING NORTH EAST ARROW
U+292E  ?   NORTH EAST ARROW CROSSING SOUTH EAST ARROW
U+292F  ?   FALLING DIAGONAL CROSSING NORTH EAST ARROW
U+2930  ?   RISING DIAGONAL CROSSING SOUTH EAST ARROW
U+2931  ?   NORTH EAST ARROW CROSSING NORTH WEST ARROW
U+2932  ?   NORTH WEST ARROW CROSSING NORTH EAST ARROW
U+2933  ?   WAVE ARROW POINTING DIRECTLY RIGHT
U+2934  ?   ARROW POINTING RIGHTWARDS THEN CURVING UPWARDS
U+2935  ?   ARROW POINTING RIGHTWARDS THEN CURVING DOWNWARDS
U+2936  ?   ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
U+2937  ?   ARROW POINTING DOWNWARDS THEN CURVING RIGHTWARDS
U+2938  ?   RIGHT-SIDE ARC CLOCKWISE ARROW
U+2939  ?   LEFT-SIDE ARC ANTICLOCKWISE ARROW
U+293A  ?   TOP ARC ANTICLOCKWISE ARROW
U+293B  ?   BOTTOM ARC ANTICLOCKWISE ARROW
U+293C  ?   TOP ARC CLOCKWISE ARROW WITH MINUS
U+293D  ?   TOP ARC ANTICLOCKWISE ARROW WITH PLUS
U+293E  ?   LOWER RIGHT SEMICIRCULAR CLOCKWISE ARROW
U+293F  ?   LOWER LEFT SEMICIRCULAR ANTICLOCKWISE ARROW
U+2940  ?   ANTICLOCKWISE CLOSED CIRCLE ARROW
U+2941  ?   CLOCKWISE CLOSED CIRCLE ARROW
U+2942  ?   RIGHTWARDS ARROW ABOVE SHORT LEFTWARDS ARROW
U+2943  ?   LEFTWARDS ARROW ABOVE SHORT RIGHTWARDS ARROW
U+2944  ?   SHORT RIGHTWARDS ARROW ABOVE LEFTWARDS ARROW
U+2945  ?   RIGHTWARDS ARROW WITH PLUS BELOW
U+2946  ?   LEFTWARDS ARROW WITH PLUS BELOW
U+2962  ?   LEFTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB DOWN
U+2963  ?   UPWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT
U+2964  ?   RIGHTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB DOWN
U+2965  ?   DOWNWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT
U+2966  ?   LEFTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB UP
U+2967  ?   LEFTWARDS HARPOON WITH BARB DOWN ABOVE RIGHTWARDS HARPOON WITH BARB DOWN
U+2968  ?   RIGHTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB UP
U+2969  ?   RIGHTWARDS HARPOON WITH BARB DOWN ABOVE LEFTWARDS HARPOON WITH BARB DOWN
U+296A  ?   LEFTWARDS HARPOON WITH BARB UP ABOVE LONG DASH
U+296B  ?   LEFTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH
U+296C  ?   RIGHTWARDS HARPOON WITH BARB UP ABOVE LONG DASH
U+296D  ?   RIGHTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH
U+296E  ?   UPWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT
U+296F  ?   DOWNWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT
U+2989  ?   Z NOTATION LEFT BINDING BRACKET
U+298A  ?   Z NOTATION RIGHT BINDING BRACKET
U+2991  ?   LEFT ANGLE BRACKET WITH DOT
U+2992  ?   RIGHT ANGLE BRACKET WITH DOT
U+2993  ?   LEFT ARC LESS-THAN BRACKET
U+2994  ?   RIGHT ARC GREATER-THAN BRACKET
U+2995  ?   DOUBLE LEFT ARC GREATER-THAN BRACKET
U+2996  ?   DOUBLE RIGHT ARC LESS-THAN BRACKET
U+29A8  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND RIGHT
U+29A9  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND LEFT
U+29AA  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND RIGHT
U+29AB  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND LEFT
U+29AC  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND UP
U+29AD  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND UP
U+29AE  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND DOWN
U+29AF  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND DOWN
U+29BE  ?   CIRCLED WHITE BULLET
U+29BF  ?   CIRCLED BULLET
U+29C9  ?   TWO JOINED SQUARES
U+29CE  ?   RIGHT TRIANGLE ABOVE LEFT TRIANGLE
U+29CF  ?   LEFT TRIANGLE BESIDE VERTICAL BAR
U+29D0  ?   VERTICAL BAR BESIDE RIGHT TRIANGLE
U+29D1  ?   BOWTIE WITH LEFT HALF BLACK
U+29D2  ?   BOWTIE WITH RIGHT HALF BLACK
U+29D3  ?   BLACK BOWTIE
U+29D4  ?   TIMES WITH LEFT HALF BLACK
U+29D5  ?   TIMES WITH RIGHT HALF BLACK
U+29D6  ?   WHITE HOURGLASS
U+29D7  ?   BLACK HOURGLASS
U+29E8  ?   DOWN-POINTING TRIANGLE WITH LEFT HALF BLACK
U+29E9  ?   DOWN-POINTING TRIANGLE WITH RIGHT HALF BLACK
U+29EA  ?   BLACK DIAMOND WITH DOWN ARROW
U+29EB  ?   BLACK LOZENGE
U+29EC  ?   WHITE CIRCLE WITH DOWN ARROW
U+29ED  ?   BLACK CIRCLE WITH DOWN ARROW
U+29F4  ?   RULE-DELAYED
U+29FC  ?   LEFT-POINTING CURVED ANGLE BRACKET
U+29FD  ?   RIGHT-POINTING CURVED ANGLE BRACKET
U+29FE  ?   TINY
U+29FF  ?   MINY
U+2B00  ?   NORTH EAST WHITE ARROW
U+2B01  ?   NORTH WEST WHITE ARROW
U+2B02  ?   SOUTH EAST WHITE ARROW
U+2B03  ?   SOUTH WEST WHITE ARROW
U+2B04  ?   LEFT RIGHT WHITE ARROW
U+2B05  ?   LEFTWARDS BLACK ARROW
U+2B06  ?   UPWARDS BLACK ARROW
U+2B07  ?   DOWNWARDS BLACK ARROW
U+2B08  ?   NORTH EAST BLACK ARROW
U+2B09  ?   NORTH WEST BLACK ARROW
U+2B0A  ?   SOUTH EAST BLACK ARROW
U+2B0B  ?   SOUTHWEST BLACK ARROW
U+2B0C  ?   LEFT RIGHT BLACK ARROW
U+2B0D  ?   UP DOWN BLACK ARROW
U+2B0E  ?   RIGHTWARDS ARROW WITH TIP DOWNWARDS
U+2B0F  ?   RIGHTWARDS ARROW WITH TIP UPWARDS
U+2B10  ?   LEFTWARDS ARROW WITH TIP DOWNWARDS
U+2B11  ?   LEFTWARDS ARROW WITH TIP UPWARDS
U+2B12  ?   SQUARE WITH TOP HALF BLACK
U+2B13  ?   SQUARE WITH BOTTOM HALF BLACK
U+2B14  ?   SQUARE WITH UPPER RIGHT DIAGONAL HALF BLACK
U+2B15  ?   SQUARE WITH LOWER LEFT DIAGONAL HALF BLACK
U+2B16  ?   DIAMOND WITH LEFT HALF BLACK
U+2B17  ?   DIAMOND WITH RIGHT HALF BLACK
U+2B18  ?   DIAMOND WITH TOP HALF BLACK
U+2B19  ?   DIAMOND WITH BOTTOM HALF BLACK
U+2B1A  ?   DOTTED SQUARE
U+2B1B  ?   BLACK LARGE SQUARE
U+2B1C  ?   WHITE LARGE SQUARE
U+2B1D  ?   BLACK VERY SMALL SQUARE
U+2B1E  ?   WHITE VERY SMALL SQUARE
U+2B1F  ?   BLACK PENTAGON
U+2B20  ?   WHITE PENTAGON
U+2B21  ?   WHITE HEXAGON
U+2B22  ?   BLACK HEXAGON
U+2B23  ?   HORIZONTAL BLACK HEXAGON
U+2B24  ?   BLACK LARGE CIRCLE
U+2B25  ?   BLACK MEDIUM DIAMOND
U+2B26  ?   WHITE MEDIUM DIAMOND
U+2B27  ?   BLACK MEDIUM LOZENGE
U+2B28  ?   WHITE MEDIUM LOZENGE
U+2B29  ?   BLACK SMALL DIAMOND
U+2B2A  ?   BLACK SMALL LOZENGE
U+2B2B  ?   WHITE SMALL LOZENGE
U+2B30  ?   LEFT ARROW WITH SMALL CIRCLE
U+2B31  ?   THREE LEFTWARDS ARROWS
U+2B32  ?   LEFT ARROW WITH CIRCLED PLUS
U+2B33  ?   LONG LEFTWARDS SQUIGGLE ARROW
U+2B34  ?   LEFTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE
U+2B35  ?   LEFTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE
U+2B36  ?   LEFTWARDS TWO-HEADED ARROW FROM BAR
U+2B37  ?   LEFTWARDS TWO-HEADED TRIPLE DASH ARROW
U+2B38  ?   LEFTWARDS ARROW WITH DOTTED STEM
U+2B39  ?   LEFTWARDS ARROW WITH TAIL WITH VERTICAL STROKE
U+2B3A  ?   LEFTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2B3B  ?   LEFTWARDS TWO-HEADED ARROW WITH TAIL
U+2B3C  ?   LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE
U+2B3D  ?   LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2B3E  ?   LEFTWARDS ARROW THROUGH X
U+2B3F  ?   WAVE ARROW POINTING DIRECTLY LEFT
U+2B40  ?   EQUALS SIGN ABOVE LEFTWARDS ARROW
U+2B41  ?   REVERSE TILDE OPERATOR ABOVE LEFTWARDS ARROW
U+2B42  ?   LEFTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO
U+2B43  ?   RIGHTWARDS ARROW THROUGH GREATER-THAN
U+2B44  ?   RIGHTWARDS ARROW THROUGH SUPERSET
U+2B45  ?   LEFTWARDS QUADRUPLE ARROW
U+2B46  ?   RIGHTWARDS QUADRUPLE ARROW
U+2B47  ?   REVERSE TILDE OPERATOR ABOVE RIGHTWARDS ARROW
U+2B48  ?   RIGHTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO
U+2B49  ?   TILDE OPERATOR ABOVE LEFTWARDS ARROW
U+2B4A  ?   LEFTWARDS ARROW ABOVE ALMOST EQUAL TO
U+2B4B  ?   LEFTWARDS ARROW ABOVE REVERSE TILDE OPERATOR
U+2B4C  ?   RIGHTWARDS ARROW ABOVE REVERSE TILDE OPERATOR
U+2B50  ?   WHITE MEDIUM STAR
U+2B51  ?   BLACK SMALL STAR
U+2B52  ?   WHITE SMALL STAR
U+2B53  ?   BLACK RIGHT-POINTING PENTAGON
U+2B54  ?   WHITE RIGHT-POINTING PENTAGON
U+2B55  ?   HEAVY LARGE CIRCLE
U+2B56  ?   HEAVY OVAL WITH OVAL INSIDE
U+2B57  ?   HEAVY CIRCLE WITH CIRCLE INSIDE
U+2B58  ?   HEAVY CIRCLE
U+2B59  ?   HEAVY CIRCLED SALTIRE

OPTION 2: PURE CSS CHEVRONS

I recently made an article about creating chevrons efficiently using only CSS (No images required).

How to simply alter:

  • ROTATION
  • THICKNESS
  • COLOR
  • SIZE

CLICK FOR DEMO ON JSFIDDLE


enter image description here


CSS (Efficient with cross browser support)

_x000D_
_x000D_
.Chevron{_x000D_
    position:relative;_x000D_
    display:block;_x000D_
    height:50px;/*height should be double border*/_x000D_
}_x000D_
.Chevron:before,_x000D_
.Chevron:after{_x000D_
    position:absolute;_x000D_
    display:block;_x000D_
    content:"";_x000D_
    border:25px solid transparent;/*adjust size*/_x000D_
}_x000D_
/* Replace all text `top` below with left/right/bottom to rotate the chevron */_x000D_
.Chevron:before{_x000D_
    top:0;_x000D_
    border-top-color:#b00;/*Chevron Color*/_x000D_
}_x000D_
.Chevron:after{_x000D_
    top:-10px;/*adjust thickness*/_x000D_
    border-top-color:#fff;/*Match background colour*/_x000D_
}
_x000D_
<i class="Chevron"></i>
_x000D_
_x000D_
_x000D_


OPTION 3: CSS BASE64 IMAGE ICONS

UP/DOWN UP/DOWN

DOWN DOWN

UP UP

Using only a few lines of CSS we can encode our images into base64.


CLICK FOR DEMO ON JSFIDDLE


PROS

  • No need to include additional resources in the form of images or fonts.
  • Supports full alpha transparency.
  • Full cross-browser support.
  • Small images/icons can be stored in a database.

CONS

  • Updating/editing can become a hassle.
  • Not suitable for large images due to excessive code markup that's generated.

CSS

.sorting,
.sorting_asc,
.sorting_desc{
    padding:4px 21px 4px 4px;
    cursor:pointer;
}
.sorting{
    background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIUnC2nKLnT4or00PvyrQwrPzUZshQAOw==) no-repeat center right;
}
.sorting_asc{
    background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIRnC2nKLnT4or00Puy3rx7VQAAOw==) no-repeat center right;
}
.sorting_desc{
    background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIPnI+py+0/hJzz0IruwjsVADs=) no-repeat center right;
}

Last element in .each() set

A shorter answer from here, adapted to this question:

var arr = $('.requiredText');
arr.each(function(index, item) {
   var is_last_item = (index == (arr.length - 1));
});

Just for completeness.

What does $1 mean in Perl?

The $number variables contain the parts of the string that matched the capture groups ( ... ) in the pattern for your last regex match if the match was successful.

For example, take the following string:

$text = "the quick brown fox jumps over the lazy dog.";

After the statement

$text =~ m/ (b.+?) /;

$1 equals the text "brown".

SQL Server: Invalid Column Name

I had a similar problem.

Issue was there was a trigger on the table that would write changes to an audit log table. Columns were missing in audit log table.

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

For me, the problem occurs when I've downloaded macOS Compressed Archive which underlying directory contains

jdk-11.0.8.jdk
- Contents
  - Home
    - bin
    - ...
  - MacOS
  - _CodeSignature

So, to solve the problem, JAVA_HOME should be pointed directly to /Path-to-JDK/Contents/Home.

How to import existing Android project into Eclipse?

Solved: If you want to "Create project from existing source", you need to create a new directory and then put the project directory tree into that new directory. Then point to the new directory when importing.

Angular 2 Routing run in new tab

Late to this one, but I just discovered an alternative way of doing it:

On your template,

<a (click)="navigateAssociates()">Associates</a> 

And on your component.ts, you can use serializeUrl to convert the route into a string, which can be used with window.open()

navigateAssociates() {
  const url = this.router.serializeUrl(
    this.router.createUrlTree(['/page1'])
  );

  window.open(url, '_blank');
}

How to disable a ts rule for a specific line?

@ts-expect-error

TS 3.9 introduces a new magic comment. @ts-expect-error will:

  • have same functionality as @ts-ignore
  • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
if (false) {
  // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
  console.log("hello"); // compiles
}

// If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
let flag = true;
// ...
if (flag) {
  // @ts-expect-error
  // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
  console.log("hello"); 
}

Alternatives

@ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

? Use any type

// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;

// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;

? Augment JQueryStatic interface

// ./global.d.ts
interface JQueryStatic {
  summernote: any;
}

// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works

In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

React : difference between <Route exact path="/" /> and <Route path="/" />

In short, if you have multiple routes defined for your app's routing, enclosed with Switch component like this;

<Switch>

  <Route exact path="/" component={Home} />
  <Route path="/detail" component={Detail} />

  <Route exact path="/functions" component={Functions} />
  <Route path="/functions/:functionName" component={FunctionDetails} />

</Switch>

Then you have to put exact keyword to the Route which it's path is also included by another Route's path. For example home path / is included in all paths so it needs to have exact keyword to differentiate it from other paths which start with /. The reason is also similar to /functions path. If you want to use another route path like /functions-detail or /functions/open-door which includes /functions in it then you need to use exact for the /functions route.

How to post data using HttpClient?

Try to use this:

using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
    {
        //add parameters on request
        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("test", "test"),
            new KeyValuePair<string, string>("test1", "test1")
        };

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
        client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
        client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
        client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
        //client.DefaultRequestHeaders.Add("Accept", "*/*");

        client.Timeout = TimeSpan.FromMilliseconds(10000);

        var res = await client.PostAsync("", new FormUrlEncodedContent(body));

        if (res.IsSuccessStatusCode)
        {
            var exec = await res.Content.ReadAsStringAsync();
            Console.WriteLine(exec);
        }                    
    }
}

Set 4 Space Indent in Emacs in Text Mode

(setq-default tab-width 4)
(setq-default indent-tabs-mode nil)

How do I determine the size of my array in C?

The simplest Answer:

#include <stdio.h>

int main(void) {

    int a[] = {2,3,4,5,4,5,6,78,9,91,435,4,5,76,7,34};//for Example only
    int size;

    size = sizeof(a)/sizeof(a[0]);//Method

    printf ("size = %d",size);
    return 0;
}

JQuery Validate Dropdown list

    <div id="msg"></div>
<!-- put above tag on body to see selected value or error -->
<script>
    $(function(){
        $("#HoursEntry").change(function(){
            var HoursEntry = $("#HoursEntry option:selected").val();
            console.log(HoursEntry);
            if(HoursEntry == "")
            {
                $("#msg").html("Please select at least One option");
                return false;
            }
            else
            {
                $("#msg").html("selected val is  "+HoursEntry);
            }
        });
    });
</script>

How to create multiple output paths in Webpack config

If it's not obvious after all the answers you can also output to a completely different directories (for example a directory outside your standard dist folder). You can do that by using your root as a path (because you only have one path) and by moving the full "directory part" of your path to the entry option (because you can have multiple entries):

entry: {
  'dist/main': './src/index.js',
  'docs/main': './src/index.js'
},
output: {
  filename: '[name].js',
  path: path.resolve(__dirname, './'),
}

This config results in the ./dist/main.js and ./docs/main.js being created.

How to clean old dependencies from maven repositories?

  1. Download all actual dependencies of your projects

    find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
    
  2. Move your local maven repository to temporary location

    mv ~/.m2 ~/saved-m2
    
  3. Rename all files maven-metadata-central.xml* from saved repository into maven-metadata.xml*

    find . -type f -name "maven-metadata-central.xml*" -exec rename -v -- 's/-central//' '{}' \;
    
  4. To setup the modified copy of the local repository as a mirror, create the directory ~/.m2 and the file ~/.m2/settings.xml with the following content (replacing user with your username):

    <settings>
     <mirrors>
      <mirror>
       <id>mycentral</id>
       <name>My Central</name>
       <url>file:/home/user/saved-m2/</url>
       <mirrorOf>central</mirrorOf>
      </mirror>
     </mirrors>
    </settings>
    
  5. Resolve your projects dependencies again:

    find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
    
  6. Now you have local maven repository with minimal of necessary artifacts. Remove local mirror from config file and from file system.

Concatenate rows of two dataframes in pandas

Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)

import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1

u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0

#option 1
#keep index of t
u.index = t.index 

#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)

#now concat will keep number of rows 
r=pd.concat([t,u], axis=1)

How to match all occurrences of a regex

if you have a regexp with groups:

str="A 54mpl3 string w1th 7 numbers scatter3r ar0und"
re=/(\d+)[m-t]/

you can use String's scan method to find matching groups:

str.scan re
#> [["54"], ["1"], ["3"]]

To find the matching pattern:

str.to_enum(:scan,re).map {$&}
#> ["54m", "1t", "3r"]

How to restore to a different database in sql server?

It is actually a bit simpler than restoring to the same server. Basically, you just walk through the "Restore Database" options. Here is a tutorial for you:

http://www.techrepublic.com/blog/window-on-windows/how-do-i-restore-a-sql-server-database-to-a-new-server/454

Especially since this is a non-production restore, you can feel comfortable just trying it out without worrying about the details too much. Just put your SQL files where you want them on your new server and give it whatever name you want and you are good to go.

Javascript dynamic array of strings

You can go with inserting data push, this is going to be doing in order

var arr = Array();
function arrAdd(value){
    arr.push(value);
}

Call js-function using JQuery timer

jQuery 1.4 also includes a .delay( duration, [ queueName ] ) method if you only need it to trigger once and have already started using that version.

$('#foo').slideUp(300).delay(800).fadeIn(400);

http://api.jquery.com/delay/

Ooops....my mistake you were looking for an event to continue triggering. I'll leave this here, someone may find it helpful.

How do I increase the contrast of an image in Python OpenCV

For Python, I haven't found an OpenCV function that provides contrast. As others have suggested, there are some techniques to automatically increase contrast using a very simple formula.

In the official OpenCV docs, it is suggested that this equation can be used to apply both contrast and brightness at the same time:

new_img = alpha*old_img + beta

where alpha corresponds to a contrast and beta is brightness. Different cases

alpha 1  beta 0      --> no change  
0 < alpha < 1        --> lower contrast  
alpha > 1            --> higher contrast  
-127 < beta < +127   --> good range for brightness values

In C/C++, you can implement this equation using cv::Mat::convertTo, but we don't have access to that part of the library from Python. To do it in Python, I would recommend using the cv::addWeighted function, because it is quick and it automatically forces the output to be in the range 0 to 255 (e.g. for a 24 bit color image, 8 bits per channel). You could also use convertScaleAbs as suggested by @nathancy.

import cv2
img = cv2.imread('input.png')
# call addWeighted function. use beta = 0 to effectively only operate one one image
out = cv2.addWeighted( img, contrast, img, 0, brightness)
output = cv2.addWeighted

The above formula and code is quick to write and will make changes to brightness and contrast. But they yield results that are significantly different than photo editing programs. The rest of this answer will yield a result that will reproduce the behavior in the GIMP and also LibreOffice brightness and contrast. It's more lines of code, but it gives a nice result.

Contrast

In the GIMP, contrast levels go from -127 to +127. I adapted the formulas from here to fit in that range.

f = 131*(contrast + 127)/(127*(131-contrast))
new_image = f*(old_image - 127) + 127 = f*(old_image) + 127*(1-f)

To figure out brightness, I figured out the relationship between brightness and levels and used information in this levels post to arrive at a solution.

#pseudo code
if brightness > 0
    shadow = brightness
    highlight = 255
else:
    shadow = 0
    highlight = 255 + brightness
new_img = ((highlight - shadow)/255)*old_img + shadow

brightness and contrast in Python and OpenCV

Putting it all together and adding using the reference "mandrill" image from USC SIPI:

import cv2
import numpy as np

# Open a typical 24 bit color image. For this kind of image there are
# 8 bits (0 to 255) per color channel
img = cv2.imread('mandrill.png')  # mandrill reference image from USC SIPI

s = 128
img = cv2.resize(img, (s,s), 0, 0, cv2.INTER_AREA)

def apply_brightness_contrast(input_img, brightness = 0, contrast = 0):
    
    if brightness != 0:
        if brightness > 0:
            shadow = brightness
            highlight = 255
        else:
            shadow = 0
            highlight = 255 + brightness
        alpha_b = (highlight - shadow)/255
        gamma_b = shadow
        
        buf = cv2.addWeighted(input_img, alpha_b, input_img, 0, gamma_b)
    else:
        buf = input_img.copy()
    
    if contrast != 0:
        f = 131*(contrast + 127)/(127*(131-contrast))
        alpha_c = f
        gamma_c = 127*(1-f)
        
        buf = cv2.addWeighted(buf, alpha_c, buf, 0, gamma_c)

    return buf


font = cv2.FONT_HERSHEY_SIMPLEX
fcolor = (0,0,0)

blist = [0, -127, 127,   0,  0, 64] # list of brightness values
clist = [0,    0,   0, -64, 64, 64] # list of contrast values


out = np.zeros((s*2, s*3, 3), dtype = np.uint8)

for i, b in enumerate(blist):
    c = clist[i]
    print('b, c:  ', b,', ',c)
    row = s*int(i/3)
    col = s*(i%3)
    
    print('row, col:   ', row, ', ', col)
    
    out[row:row+s, col:col+s] = apply_brightness_contrast(img, b, c)
    msg = 'b %d' % b
    cv2.putText(out,msg,(col,row+s-22), font, .7, fcolor,1,cv2.LINE_AA)
    msg = 'c %d' % c
    cv2.putText(out,msg,(col,row+s-4), font, .7, fcolor,1,cv2.LINE_AA)
    
    cv2.putText(out, 'OpenCV',(260,30), font, 1.0, fcolor,2,cv2.LINE_AA)

cv2.imwrite('out.png', out)

enter image description here

I manually processed the images in the GIMP and added text tags in Python/OpenCV:
enter image description here

Note: @UtkarshBhardwaj has suggested that Python 2.x users must cast the contrast correction calculation code into float for getting floating result, like so:

...
if contrast != 0:
        f = float(131*(contrast + 127))/(127*(131-contrast))
...

Python argparse command line flags without arguments

As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look here (specifically store_true and store_false)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')

where action='store_true' implies default=False.

Conversely, you could haveaction='store_false', which implies default=True.

Using {% url ??? %} in django templates

Judging from your example, shouldn't it be {% url myproject.login.views.login_view %} and end of story? (replace myproject with your actual project name)

Connecting to SQL Server using windows authentication

Use this code:

        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = @"Data Source=HOSTNAME\SQLEXPRESS; Initial Catalog=DataBase; Integrated Security=True";
        conn.Open();
        MessageBox.Show("Connection Open  !");
        conn.Close();

UNIX export command

Unix

The commands env, set, and printenv display all environment variables and their values. env and set are also used to set environment variables and are often incorporated directly into the shell. printenv can also be used to print a single variable by giving that variable name as the sole argument to the command.

In Unix, the following commands can also be used, but are often dependent on a certain shell.

export VARIABLE=value  # for Bourne, bash, and related shells
setenv VARIABLE value  # for csh and related shells

You can have a look at this at

Regular Expression usage with ls

You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:

$ ls | egrep '.+\..+'

jQuery change event on dropdown

You should've kept that DOM ready function

$(function() {
    $("#projectKey").change(function() {
        alert( $('option:selected', this).text() );
    });
});

The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body> tag

Getting vertical gridlines to appear in line plot in matplotlib

maybe this can solve the problem: matplotlib, define size of a grid on a plot

ax.grid(True, which='both')

The truth is that the grid is working, but there's only one v-grid in 00:00 and no grid in others. I meet the same problem that there's only one grid in Nov 1 among many days.

Python - How do you run a .py file?

Since you seem to be on windows you can do this so python <filename.py>. Check that python's bin folder is in your PATH, or you can do c:\python23\bin\python <filename.py>. Python is an interpretive language and so you need the interpretor to run your file, much like you need java runtime to run a jar file.

How to Remove Line Break in String

Replace(yourString, vbNewLine, "", , , vbTextCompare)

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

Is there any native DLL export functions viewer?

DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.

This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.

enter image description here

How to dynamically allocate memory space for a string and get that string from user?

First, define a new function to read the input (according to the structure of your input) and store the string, which means the memory in stack used. Set the length of string to be enough for your input.

Second, use strlen to measure the exact used length of string stored before, and malloc to allocate memory in heap, whose length is defined by strlen. The code is shown below.

int strLength = strlen(strInStack);
if (strLength == 0) {
    printf("\"strInStack\" is empty.\n");
}
else {
    char *strInHeap = (char *)malloc((strLength+1) * sizeof(char));
    strcpy(strInHeap, strInStack);
}
return strInHeap;

Finally, copy the value of strInStack to strInHeap using strcpy, and return the pointer to strInHeap. The strInStack will be freed automatically because it only exits in this sub-function.

Removing packages installed with go get

You can delete the archive files and executable binaries that go install (or go get) produces for a package with go clean -i importpath.... These normally reside under $GOPATH/pkg and $GOPATH/bin, respectively.

Be sure to include ... on the importpath, since it appears that, if a package includes an executable, go clean -i will only remove that and not archive files for subpackages, like gore/gocode in the example below.

Source code then needs to be removed manually from $GOPATH/src.

go clean has an -n flag for a dry run that prints what will be run without executing it, so you can be certain (see go help clean). It also has a tempting -r flag to recursively clean dependencies, which you probably don't want to actually use since you'll see from a dry run that it will delete lots of standard library archive files!

A complete example, which you could base a script on if you like:

$ go get -u github.com/motemen/gore

$ which gore
/Users/ches/src/go/bin/gore

$ go clean -i -n github.com/motemen/gore...
cd /Users/ches/src/go/src/github.com/motemen/gore
rm -f gore gore.exe gore.test gore.test.exe commands commands.exe commands_test commands_test.exe complete complete.exe complete_test complete_test.exe debug debug.exe helpers_test helpers_test.exe liner liner.exe log log.exe main main.exe node node.exe node_test node_test.exe quickfix quickfix.exe session_test session_test.exe terminal_unix terminal_unix.exe terminal_windows terminal_windows.exe utils utils.exe
rm -f /Users/ches/src/go/bin/gore
cd /Users/ches/src/go/src/github.com/motemen/gore/gocode
rm -f gocode.test gocode.test.exe
rm -f /Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore/gocode.a

$ go clean -i github.com/motemen/gore...

$ which gore

$ tree $GOPATH/pkg/darwin_amd64/github.com/motemen/gore
/Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore

0 directories, 0 files

# If that empty directory really bugs you...
$ rmdir $GOPATH/pkg/darwin_amd64/github.com/motemen/gore

$ rm -rf $GOPATH/src/github.com/motemen/gore

Note that this information is based on the go tool in Go version 1.5.1.

How to use Tomcat 8 in Eclipse?

To add the Tomcat 9.0 (Tomcat build from the trunk) as a server in Eclipse.

Update the ServerInfo.properties file properties as below.

server.info=Apache Tomcat/@VERSION@
server.number=@VERSION_NUMBER@
server.built=@VERSION_BUILT@


server.info=Apache Tomcat/7.0.57
server.number=7.0.57.0
server.built=Nov 3 2014 08:39:16 UTC

Build the tomcat server from trunk and add the server as tomcat7 instance in Eclipse.

ServerInfo.properties file location : \tomcat\java\org\apache\catalina\util\ServerInfo.properties

SQL select * from column where year = 2010

its just simple

  select * from myTable where year(columnX) = 2010

PHP mPDF save file as PDF

Try this:

$mpdf->Output('my_filename.pdf','D'); 

because:

D - means Download
F - means File-save only

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

Display HTML form values in same page after submit using Ajax

<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>

<!--Insert more code here-->


<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">

Next time you ask a question here, include more detail and what you have tried.

Subscripts in plots in R

If you are looking to have multiple subscripts in one text then use the star(*) to separate the sections:

plot(1:10, xlab=expression('hi'[5]*'there'[6]^8*'you'[2]))

LocalDate to java.util.Date and vice versa simplest conversion?

tl;dr

Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By 'simple', I mean simpler than this

Nope. You did it properly, and as concisely as possible.

java.util.Date.from(                     // Convert from modern java.time class to troublesome old legacy class.  DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
    myLocalDate                          // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC. 
    .atStartOfDay(                       // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
        ZoneId.of( "America/Montreal" )  // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as “PST”, “CST”, “IST”. 
    )                                    // Produce a `ZonedDateTime` object. 
    .toInstant()                         // Extract an `Instant` object, a moment always in UTC.
)

Read below for issues, and then think about it. How could it be simpler? If you ask me what time does a date start, how else could I respond but ask you “Where?”?. A new day dawns earlier in Paris FR than in Montréal CA, and still earlier in Kolkata IN, and even earlier in Auckland NZ, all different moments.

So in converting a date-only (LocalDate) to a date-time we must apply a time zone (ZoneId) to get a zoned value (ZonedDateTime), and then move into UTC (Instant) to match the definition of a java.util.Date.

Details

Firstly, avoid the old legacy date-time classes such as java.util.Date whenever possible. They are poorly designed, confusing, and troublesome. They were supplanted by the java.time classes for a reason, actually, for many reasons.

But if you must, you can convert to/from java.time types to the old. Look for new conversion methods added to the old classes.

Table of all date-time types in Java, both modern and legacy

java.util.Date ? java.time.LocalDate

Keep in mind that a java.util.Date is a misnomer as it represents a date plus a time-of-day, in UTC. In contrast, the LocalDate class represents a date-only value without time-of-day and without time zone.

Going from java.util.Date to java.time means converting to the equivalent class of java.time.Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

So we need to move that Instant into a time zone. We apply ZoneId to get a ZonedDateTime.

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

From there, ask for a date-only, a LocalDate.

LocalDate ld = zdt.toLocalDate();

java.time.LocalDate ? java.util.Date

To move the other direction, from a java.time.LocalDate to a java.util.Date means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do not assume that is 00:00:00. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00. Let java.time determine that value by calling atStartOfDay on the LocalDate.

ZonedDateTime zdt = myLocalDate.atStartOfDay( z );

Now extract an Instant.

Instant instant = zdt.toInstant();

Convert that Instant to java.util.Date by calling from( Instant ).

java.util.Date d = java.util.Date.from( instant );

More info


About java.time

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

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

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

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

How to search for rows containing a substring?

Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.

http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Even if WHERE textcolumn LIKE "%SUBSTRING%" is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).

If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")

CSS full screen div with text in the middle

The accepted answer works, but if:

  • you don't know the content's dimensions
  • the content is dynamic
  • you want to be future proof

use this:

.centered {
  position: fixed; /* or absolute */
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

More information about centering content in this excellent CSS-Tricks article.


Also, if you don't need to support old browsers: a flex-box makes this a piece of cake:

.center{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

Another great guide about flexboxs from CSS Tricks; http://css-tricks.com/snippets/css/a-guide-to-flexbox/

memory error in python

If you get an unexpected MemoryError and you think you should have plenty of RAM available, it might be because you are using a 32-bit python installation.

The easy solution, if you have a 64-bit operating system, is to switch to a 64-bit installation of python.

The issue is that 32-bit python only has access to ~4GB of RAM. This can shrink even further if your operating system is 32-bit, because of the operating system overhead.

You can learn more about why 32-bit operating systems are limited to ~4GB of RAM here: https://superuser.com/questions/372881/is-there-a-technical-reason-why-32-bit-windows-is-limited-to-4gb-of-ram

Maven: mvn command not found

mvn -version

export PATH=$PATH:/opt/apache-maven-3.6.0/bin

Java program to find the largest & smallest number in n numbers without using arrays

import java.util.Scanner;

public class LargestSmallestNumbers {

    private static Scanner input;

    public static void main(String[] args) {
       int count,items;
       int newnum =0 ;
       int highest=0;
       int lowest =0;

       input = new Scanner(System.in);
       System.out.println("How many numbers you want to enter?");
       items = input.nextInt();

       System.out.println("Enter "+items+" numbers: ");


       for (count=0; count<items; count++){
           newnum = input.nextInt();               
           if (highest<newnum)
               highest=newnum;

           if (lowest==0)
               lowest=newnum;

           else if (newnum<=lowest)
               lowest=newnum;
           }

       System.out.println("The highest number is "+highest);
       System.out.println("The lowest number is "+lowest);
    }
}

push() a two-dimensional array

You have some errors in your code:

  1. Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j].
  2. You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.

One correct, although kind of verbose version, would be the following:

var r = 3; //start from rows 3

var rows = 8;
var cols = 7;

// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
  myArray.push( [] );
}

// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
{
    for (var j =  myArray[i].length; j < cols; j++)
    {
        myArray[i].push(0);
    }
}

How can I debug a .BAT script?

you can use cmd \k at the end of your script to see the error. it won't close your command prompt after the execution is done

Keep CMD open after BAT file executes

I was also confused as to why we're adding a cmd at the beginning and I was wondering if I had to open the command prompt first. What you need to do is type the full command along with cmd /k. For example assume your batch file name is "my_command.bat" which runs the command javac my_code.java then the code in your batch file should be:

cmd /k javac my_code.java

So basically there is no need to open command prompt at the current folder and type the above command but you can save this code directly in your batch file and execute it directly.

How to use jQuery to show/hide divs based on radio button selection?

Update 2015/06

As jQuery has evolved since the question was posted, the recommended approach now is using $.on

$(document).ready(function() {
    $("input[name=group2]").on( "change", function() {

         var test = $(this).val();
         $(".desc").hide();
         $("#"+test).show();
    } );
});

or outside $.ready()

$(document).on( "change", "input[name=group2]", function() { ... } );

Original answer

You should use .change() event handler:

$(document).ready(function(){ 
    $("input[name=group2]").change(function() {
        var test = $(this).val();
        $(".desc").hide();
        $("#"+test).show();
    }); 
});

should work

Mock functions in Go

Considering unit test is the domain of this question, highly recommend you to use monkey. This Package make you to mock test without changing your original source code. Compare to other answer, it's more "non-intrusive".

main

type AA struct {
 //...
}
func (a *AA) OriginalFunc() {
//...
}

mock test

var a *AA

func NewFunc(a *AA) {
 //...
}

monkey.PatchMethod(reflect.TypeOf(a), "OriginalFunc", NewFunc)

Bad side is:

  • Reminded by Dave.C, This method is unsafe. So don't use it outside of unit test.
  • Is non-idiomatic Go.

Good side is:

  • Is non-intrusive. Make you do things without changing the main code. Like Thomas said.
  • Make you change behavior of package (maybe provided by third party) with least code.

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

The other answers are great but I thought I'd take a different tact.

If all you are really looking for is to slow down a specific file in linux:

 rm slowfile; mkfifo slowfile; perl -e 'select STDOUT; $| = 1; while(<>) {print $_; sleep(1) if (($ii++ % 5) == 0); }' myfile > slowfile  &

node myprog slowfile

This will sleep 1 sec every five lines. The node program will go as slow as the writer. If it is doing other things they will continue at normal speed.

The mkfifo creates a first-in-first-out pipe. It's what makes this work. The perl line will write as fast as you want. The $|=1 says don't buffer the output.

How to pass arguments to a Button command in Tkinter?

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

I believe should fix this

How do I format currencies in a Vue component?

Try this:

methods: {
    formatPrice(value) {
        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'PHP',
            minimumFractionDigits: 2
        });
        return formatter.format(value);
    },
}

Then you can just call this like:

{{ formatPrice(item.total) }}

jquery loop on Json data using $.each

$.each(JSON.parse(result), function(i, item) {
    alert(item.number);
});

MVC 4 - how do I pass model data to a partial view?

Also, this could make it works:

@{
Html.RenderPartial("your view", your_model, ViewData);
}

or

@{
Html.RenderPartial("your view", your_model);
}

For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

Writing to a new file if it doesn't exist, and appending to a file if it does

Using the pathlib module (python's object-oriented filesystem paths)

Just for kicks, this is perhaps the latest pythonic version of the solution.

from pathlib import Path 

path = Path(f'{player}.txt')
path.touch()  # default exists_ok=True
with path.open('a') as highscore:
   highscore.write(f'Username:{player}')

How do I create/edit a Manifest file?

Go to obj folder in you app folder, then Debug. In there delete the manifest file and build again. It worked for me.

What is the best practice for creating a favicon on a web site?

I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

I got it working by selecting the original layout I had in the W / H selection. Storyboard is working as expected and the error is gone.

Be also sure that you are developing for iOS 8.0. Check that from the project's general settings.

This is where you should press.

How to change dot size in gnuplot

Use the pointtype and pointsize options, e.g.

plot "./points.dat" using 1:2 pt 7 ps 10  

where pt 7 gives you a filled circle and ps 10 is the size.

See: Plotting data.

Using <style> tags in the <body> with other HTML

When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.

Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.

If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.

Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.

Calling functions in a DLL from C++

When the DLL was created an import lib is usually automatically created and you should use that linked in to your program along with header files to call it but if not then you can manually call windows functions like LoadLibrary and GetProcAddress to get it working.

How to git commit a single file/directory

Use the -o option.

git commit -o path/to/myfile -m "the message"

-o, --only commit only specified files

This could be due to the service endpoint binding not using the HTTP protocol

I've seen this error caused by a circular reference in the object graph. Including a pointer to the parent object from a child will cause the serializer to loop, and ultimately exceed the maximum message size.

Remove specific characters from a string in Python

Here's my Python 2/3 compatible version. Since the translate api has changed.

def remove(str_, chars):
    """Removes each char in `chars` from `str_`.

    Args:
        str_: String to remove characters from
        chars: String of to-be removed characters

    Returns:
        A copy of str_ with `chars` removed

    Example:
            remove("What?!?: darn;", " ?.!:;") => 'Whatdarn'
    """
    try:
        # Python2.x
        return str_.translate(None, chars)
    except TypeError:
        # Python 3.x
        table = {ord(char): None for char in chars}
        return str_.translate(table)

Round to at most 2 decimal places (only if necessary)

Slight modification of this answer that seems to work well.

Function

function roundToStep(value, stepParam) {
   var step = stepParam || 1.0;
   var inv = 1.0 / step;
   return Math.round(value * inv) / inv;
}

Usage

roundToStep(2.55) = 3
roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55

How to set value in @Html.TextBoxFor in Razor syntax?

The problem is that you are using a lower case v.

You need to set it to Value and it should fix your issue:

@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })

How to position the Button exactly in CSS

So, the trick here is to use absolute positioning calc like this:

top: calc(50% - XYpx);
left: calc(50% - XYpx);

where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

You can do this:

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

and most of it will work (although MS support will tell you that doing this is not supported because it bypasses RBAC).

I've seen issues with some cmdlets (specifically enable/disable UMmailbox) not working with just the snapin loaded.

In Exchange 2010, they basically don't support using Powershell outside of the the implicit remoting environment of an actual EMS shell.

How to append output to the end of a text file

For example your file contains :

 1.  mangesh@001:~$ cat output.txt
    1
    2
    EOF

if u want to append at end of file then ---->remember spaces between 'text' >> 'filename'

  2. mangesh@001:~$ echo somthing to append >> output.txt|cat output.txt 
    1
    2
    EOF
    somthing to append

And to overwrite contents of file :

  3.  mangesh@001:~$ echo 'somthing new to write' > output.tx|cat output.tx
    somthing new to write

sh: 0: getcwd() failed: No such file or directory on cited drive

This can happen with symlinks sometimes. If you experience this issue and you know you are in an existing directory, but your symlink may have changed, you can use this command:

cd $(pwd)

Split comma-separated values

A way to do this without Linq & Lambdas

string source = "a,b, b, c";
string[] items = source.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

PHP: If internet explorer 6, 7, 8 , or 9

Notice the case in 'Trident':

if (isset($_SERVER['HTTP_USER_AGENT']) &&
    ((strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) || strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== false)) {   
     // IE is here :-(
    }

Check if object exists in JavaScript

for me this worked for a DOM-object:

if(document.getElementsById('IDname').length != 0 ){
   alert("object exist");
}

Ignore case in Python strings

import re
if re.match('tEXT', 'text', re.IGNORECASE):
    # is True

How do I get the localhost name in PowerShell?

All above questions are correct but if you want the hostname and domain name try this:

 [System.Net.DNS]::GetHostByName('').HostName

What is bootstrapping?

As a humble beginner in the world of programming, and flicking through all the answers here after seeing this word used a lot in apparently slightly different ways in different places, I found reading the Wikipedia page on Bootstrapping (duh! I didn't think of it either at first) is very informative to understand differences in use of this word. Could it be......on extremely rare occasions......Wikipedia might even have better explanations of certain terms than....(redacted)? Will they bring in rep points on Wikipedia though?

To me, it seems all the meanings something to do with: start with something as simple as possible Thing1, make something slightly more complex with that Thing2, and now you can use Thing2 to do some kind of tasks more efficiently and quickly than you could originally with Thing1. Then repeat from Thing2 to Thing 3 ad infinitum...

I see it as closely connected to both biological evolution and 'Layers of Abstraction' (newbies like me see, ahem, Wikipedia, cough) - the evolution from 1940's computers with switches, machine code, Assembly, C, Python, AIs you can give all kinds of complex instructions to like "make the %4^% dinner to my default &^$% requirements and clean the floor you %$£"@:~" in drunken slang English or Amazon tribal dialect without them 'raising an exception' (for newbies again...you guessed it) - missed out lot of links there due to simple ignorance.

Then in certain specific software meanings: Meaning1: Thing1 is used to load latest version of Thing2 (because of course Thing2 will be bigger than Thing1, just as Thing3 will be be bigger than Thing2).

Meaning2: Thing1 is a lower level language (closer to 1001011100....011001 than print("Hello, ", user.name)) used to write a little bit of the higher language of Thing2, then this little bit of Thing2 is used to expand Thing2 itself from baby vocabulary level towards adult vocabulary level (Thing2 starts to be processed, or to use correct technical term 'compiled', by the baby version of itself (it's a clever baby!), whereas the baby version of Thing2 itself could of course only be compiled by Thing1, cause it can't exist before it exists, right duh!), then child version of Thing2 compiles Surly Teenager version of Thing2, at which point programming community decides whether Surly Teenager's 'issues' (software term and metaphor term!) are worth spending enough time resolving to be accepted long term, or to abandon them to (not sure where to take the analogy here).

If yes, then Thing2 has 'Bootstrapped' itself (possibly a few times) from babyhood to adulthood: "the child is the father of the man" (Wordsworth, suggest don't try looking up the quote or the author on Stack Overflow).

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

select p.name
from   person p
where  instr(p.name,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

Java difference between FileWriter and BufferedWriter

In unbuffered Input/Output(FileWriter, FileReader) read or write request is handled directly by the underlying OS. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/Unbuffered.gif

This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. The BufferedReader and BufferedWriter classes provide internal character buffers. Text that’s written to a buffered writer is stored in the internal buffer and only written to the underlying writer when the buffer fills up or is flushed. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/bufferedoutput.gif

More https://hajsoftutorial.com/java-bufferedwriter/

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

Installing cmake with home-brew

Typing brew install cmake as you did installs cmake. Now you can type cmake and use it.

If typing cmake doesn’t work make sure /usr/local/bin is your PATH. You can see it with echo $PATH. If you don’t see /usr/local/bin in it add the following to your ~/.bashrc:

export PATH="/usr/local/bin:$PATH"

Then reload your shell session and try again.


(all the above assumes Homebrew is installed in its default location, /usr/local. If not you’ll have to replace /usr/local with $(brew --prefix) in the export line)

How to serialize an object to XML without getting xmlns="..."?

If you want to get rid of the extra xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xmlns:xsd="http://www.w3.org/2001/XMLSchema", but still keep your own namespace xmlns="http://schemas.YourCompany.com/YourSchema/", you use the same code as above except for this simple change:

//  Add lib namespace with empty prefix  
ns.Add("", "http://schemas.YourCompany.com/YourSchema/");   

Using port number in Windows host file

  1. Install Redirector
  2. Click Edit redirects -> Create New Redirect

enter image description here

How to bring view in front of everything?

If you are using ConstraintLayout, just put the element after the other elements to make it on front than the others

How to implement a read only property

C# 6.0 adds readonly auto properties

public object MyProperty { get; }

So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.


Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.

Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.

Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.

Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.

Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.

But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.

IntelliJ IDEA JDK configuration on Mac OS

Quite late to this party, today I had the same problem. The right answer on macOs I think is use jenv

brew install jenv openjdk@11
jenv add /usr/local/opt/openjdk@11

And then add into Intellij IDEA as new SDK the following path:

~/.jenv/versions/11/libexec/openjdk.jdk/Contents/Home/

Removing first x characters from string?

Example to show last 3 digits of account number.

x = '1234567890'   
x.replace(x[:7], '')

o/p: '890'

How do I add space between items in an ASP.NET RadioButtonList

Even easier...

ASP.NET

<asp:RadioButtonList runat="server" ID="MyRadioButtonList" RepeatDirection="Horizontal" CssClass="FormatRadioButtonList"> ...

CSS

.FormatRadioButtonList label
{
  margin-right: 15px;
}

Count the number of commits on a Git branch

To count the commits for the branch you are on:

git rev-list --count HEAD

for a branch

git rev-list --count <branch-name>

If you want to count the commits on a branch that are made since you created the branch

git rev-list --count HEAD ^<branch-name>

This will count all commits ever made that are not on the branch-name as well.

Examples

git checkout master
git checkout -b test
<We do 3 commits>
git rev-list --count HEAD ^master

Result: 3

If your branch comes of a branch called develop:

git checkout develop
git checkout -b test
<We do 3 commits>
git rev-list --count HEAD ^develop

Result: 3

Ignoring Merges

If you merge another branch into the current branch without fast forward and you do the above, the merge is also counted. This is because for git a merge is a commit.

If you don't want to count these commits add --no-merges:

git rev-list --no-merges --count HEAD ^develop

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

(Linux/WSL at least) From the browser at bitbucket.org, create an empty repo with the same name as your local repo, follow the instructions proposed by bitbucket for importing a local repo (two commands to type).

Array as session variable

Yes, PHP supports arrays as session variables. See this page for an example.

As for your second question: once you set the session variable, it will remain the same until you either change it or unset it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.

Gradle version 2.2 is required. Current version is 2.10

Based on https://developer.android.com/studio/releases/gradle-plugin.html ...

The following table lists which version of Gradle is required for each version of the Android plugin for Gradle. For the best performance, you should use the latest possible version of both Gradle and the Android plugin.

So, the Plugin version with Required Gradle version should be match.

enter image description here

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

If you use pip version of tensorflow, it means it's already compiled and you are just installing it. Basically you install tensorflow-gpu, but when you download it from repository and trying to build, you should build it with CPU AVX support. If you ignore it, you will get the warning every time when you run on cpu.

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

jQuery equivalent to Prototype array.last()

I use this:

array.reverse()[0]

You reverse the array with reverse() and then pick the first item of the reversed version with [0], that is the last one of the original array.

You can use this code if you don't care that the array gets reversed of course, because it will remain so.

How to get the system uptime in Windows?

Two ways to do that..

Option 1:

1.  Go to "Start" -> "Run".

2.  Write "CMD" and press on "Enter" key.

3.  Write the command "net statistics server" and press on "Enter" key.

4.  The line that start with "Statistics since …" provides the time that the server was up from.


  The command "net stats srv" can be use instead.

Option 2:

Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher

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

Hope it helped you!!

Escaping backslash in string - javascript

For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.

This question already mentions, and links to other Stack Overflow questions regarding this topic.


Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.

string = string.split("\\");

In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.

So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.

What processes are using which ports on unix?

Try pfiles PID to show all open files for a process.

How to find time complexity of an algorithm

Taken from here - Introduction to Time Complexity of an Algorithm

1. Introduction

In computer science, the time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input.

2. Big O notation

The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms. When expressed this way, the time complexity is said to be described asymptotically, i.e., as the input size goes to infinity.

For example, if the time required by an algorithm on all inputs of size n is at most 5n3 + 3n, the asymptotic time complexity is O(n3). More on that later.

Few more Examples:

  • 1 = O(n)
  • n = O(n2)
  • log(n) = O(n)
  • 2 n + 1 = O(n)

3. O(1) Constant Time:

An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.

Examples:

  • array: accessing any element
  • fixed-size stack: push and pop methods
  • fixed-size queue: enqueue and dequeue methods

4. O(n) Linear Time

An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.

Consider the following examples, below I am linearly searching for an element, this has a time complexity of O(n).

int find = 66;
var numbers = new int[] { 33, 435, 36, 37, 43, 45, 66, 656, 2232 };
for (int i = 0; i < numbers.Length - 1; i++)
{
    if(find == numbers[i])
    {
        return;
    }
}

More Examples:

  • Array: Linear Search, Traversing, Find minimum etc
  • ArrayList: contains method
  • Queue: contains method

5. O(log n) Logarithmic Time:

An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size.

Example: Binary Search

Recall the "twenty questions" game - the task is to guess the value of a hidden number in an interval. Each time you make a guess, you are told whether your guess is too high or too low. Twenty questions game implies a strategy that uses your guess number to halve the interval size. This is an example of the general problem-solving method known as binary search

6. O(n2) Quadratic Time

An algorithm is said to run in quadratic time if its time execution is proportional to the square of the input size.

Examples:

7. Some Useful links

How do I set the default font size in Vim?

Add Regular to syntax and use gfn:

set gfn= Monospace\ Regular:h13

count distinct values in spreadsheet

Not exactly what the user asked, but an easy way to just count unique values:

Google introduced a new function to count unique values in just one step, and you can use this as an input for other formulas:

=COUNTUNIQUE(A1:B10)

How does Python manage int and long?

On my machine:

>>> print type(1<<30)
<type 'int'>
>>> print type(1<<31)
<type 'long'>
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'long'>

Python uses ints (32 bit signed integers, I don't know if they are C ints under the hood or not) for values that fit into 32 bit, but automatically switches to longs (arbitrarily large number of bits - i.e. bignums) for anything larger. I'm guessing this speeds things up for smaller values while avoiding any overflows with a seamless transition to bignums.

Illegal Escape Character "\"

I think ("\") may be causing the problem because \ is the escape character. change it to ("\\")

Extract images from PDF without resampling, in python?

In Python with PyPDF2 and Pillow libraries it is simple:

import PyPDF2

from PIL import Image

if __name__ == '__main__':
    input1 = PyPDF2.PdfFileReader(open("input.pdf", "rb"))
    page0 = input1.getPage(0)
    xObject = page0['/Resources']['/XObject'].getObject()

    for obj in xObject:
        if xObject[obj]['/Subtype'] == '/Image':
            size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
            data = xObject[obj].getData()
            if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
                mode = "RGB"
            else:
                mode = "P"

            if xObject[obj]['/Filter'] == '/FlateDecode':
                img = Image.frombytes(mode, size, data)
                img.save(obj[1:] + ".png")
            elif xObject[obj]['/Filter'] == '/DCTDecode':
                img = open(obj[1:] + ".jpg", "wb")
                img.write(data)
                img.close()
            elif xObject[obj]['/Filter'] == '/JPXDecode':
                img = open(obj[1:] + ".jp2", "wb")
                img.write(data)
                img.close()

How to make a node.js application run permanently?

forever package worked for me, just one thing, it depends on deep-equal, so if you had issue with installing it like:

npm -g install forever

Try:

npm -g install forever [email protected]

instead.

Spring - applicationContext.xml cannot be opened because it does not exist

just change the containing package of your applicationContext.xml file.
 applicationContext.xml must be in src package not in your project package.
 e.g. 
     src(main package)
         com.yourPackageName(package within src)
         classes etc.
     applicationContext.xml(within src but outside of yourPackage or we can say 
                            parallel to yourPackage name)

What do numbers using 0x notation mean?

Literals that start with 0x are hexadecimal integers. (base 16)

The number 0x6400 is 25600.

6 * 16^3 + 4 * 16^2 = 25600

For an example including letters (also used in hexadecimal notation where A = 10, B = 11 ... F = 15)

The number 0x6BF0 is 27632.

6 * 16^3 + 11 * 16^2 + 15 * 16^1 = 27632
24576    + 2816      + 240       = 27632

What is IllegalStateException?

package com.concepttimes.java;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IllegalStateExceptionDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List al = new ArrayList();
        al.add("Sachin");
        al.add("Rahul");
        al.add("saurav");
        Iterator itr = al.iterator();  
        while (itr.hasNext()) {           
            itr.remove();
        }
    }
}

IllegalStateException signals that method has been invoked at the wrong time. In this below example, we can see that. remove() method is called at the same time element is being used in while loop.

Please refer to below link for more details. http://www.elitmuszone.com/elitmus/illegalstateexception-in-java/

How to check if a key exists in Json Object and get its value

containerObject = new JSONObject(container);
if (containerObject.has("video")) { 
   //get Value of video
}

What's the difference between deadlock and livelock?

Imagine you've thread A and thread B. They are both synchronised on the same object and inside this block there's a global variable they are both updating;

static boolean commonVar = false;
Object lock = new Object;

...

void threadAMethod(){
    ...
    while(commonVar == false){
         synchornized(lock){
              ...
              commonVar = true
         }
    }
}

void threadBMethod(){
    ...
    while(commonVar == true){
         synchornized(lock){
              ...
              commonVar = false
         }
    }
}

So, when thread A enters in the while loop and holds the lock, it does what it has to do and set the commonVar to true. Then thread B comes in, enters in the while loop and since commonVar is true now, it is be able to hold the lock. It does so, executes the synchronised block, and sets commonVar back to false. Now, thread A again gets it's new CPU window, it was about to quit the while loop but thread B has just set it back to false, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.

It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

Excel VBA - Range.Copy transpose paste

WorksheetFunction Transpose()

Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula

    =TRANSPOSE(Sheet1!A1:A5)

or if you prefer VBA:

    Dim v
    v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
    Sheet2.Range("A1").Resize(1, UBound(v)) = v

Note: alternatively you could use late-bound Application.Transpose instead.

MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.

Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365

Maven: Non-resolvable parent POM

verify if You have correct values in child POMs

GroupId
ArtefactId
Version

In Eclipse, for example, You can search for it: Eclipse: search parent pom

How to keep one variable constant with other one changing with row in excel

Use this form:

=(B0+4)/$A$0

The $ tells excel not to adjust that address while pasting the formula into new cells.

Since you are dragging across rows, you really only need to freeze the row part:

=(B0+4)/A$0

Keyboard Shortcuts

Commenters helpfully pointed out that you can toggle relative addressing for a formula in the currently selected cells with these keyboard shortcuts:

  • Windows: f4
  • Mac: CommandT

Updating to latest version of CocoaPods?

Open the Terminal -> copy below command

sudo gem install cocoapods

It will install the latest stable version of cocoapods.

after that, you need to update pod using below command

pod setup

You can check pod version using below command

pod --version

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Using INSERT INTO ... VALUES syntax like in Daniel Vassallo's answer there is one annoying limitation:

From MSDN

The maximum number of rows that can be constructed by inserting rows directly in the VALUES list is 1000

The easiest way to omit this limitation is to use derived table like:

INSERT INTO dbo.Mytable(ID, Name)
SELECT ID, Name 
FROM (
   VALUES (1, 'a'),
          (2, 'b'),
          --...
          -- more than 1000 rows
)sub (ID, Name);

LiveDemo


This will work starting from SQL Server 2008+

How can I create a dynamic button click event on a dynamic button?

Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);

//protected void button_Click (object sender, EventArgs e) { }

Django Forms: if not valid, show form with error message

@AamirAdnan's answer missing field.label; the other way to show the errors in few lines.

{% if form.errors %}
    <!-- Error messaging -->
    <div id="errors">
        <div class="inner">
            <p>There were some errors in the information you entered. Please correct the following:</p>
            <ul>
                {% for field in form %}
                    {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
                {% endfor %}
            </ul>
        </div>
    </div>
    <!-- /Error messaging -->
{% endif %}

Android ADT error, dx.jar was not loaded from the SDK folder

Windows 7 64 bit, Intel i7

This happened to me as well after I updated the SDK to be Jelly Bean compatible. The folder platform-tools\lib was gone. I also wasn't able to uninstall/reinstall the program-tools in the SDK manager at first. It gave me the error that a particular file in the android\temp folder was not there. I had to change the permissions on the android folder to allow every action, and that solved it.

How to convert string to boolean php

Other answers are over complicating things. This question is simply logic question. Just get your statement right.

$boolString = 'false';
$result = 'true' === $boolString;

Now your answer will be either

  • false, if the string was 'false',
  • or true, if your string was 'true'.

I have to note that filter_var( $boolString, FILTER_VALIDATE_BOOLEAN ); still will be a better option if you need to have strings like on/yes/1 as alias for true.

Strip first and last character from C string

To "remove" the 1st character point to the second character:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++; /* 'N' is not in `p` */

To remove the last character replace it with a '\0'.

p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */

What is the use of DesiredCapabilities in Selenium WebDriver?

DesiredCapabilities are options that you can use to customize and configure a browser session.

You can read more about them here!

How can I open a website in my web browser using Python?

From the doc.

The webbrowser module provides a high-level interface to allow displaying Web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the right thing.

You have to import the module and use open() function. This will open https://nabinkhadka.com.np in the browser.

To open in new tab:

import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)

Also from the doc.

If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible

So according to the value of new, you can either open page in same browser window or in new tab etc.

Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

'True' and 'False' in Python

is compares identity. A string will never be identical to a not-string.

== is equality. But a string will never be equal to either True or False.

You want neither.

path = '/bla/bla/bla'

if path:
    print "True"
else:
    print "False"

How to Apply Corner Radius to LinearLayout

try this, for Programmatically to set a background with radius to LinearLayout or any View.

 private Drawable getDrawableWithRadius() {

    GradientDrawable gradientDrawable   =   new GradientDrawable();
    gradientDrawable.setCornerRadii(new float[]{20, 20, 20, 20, 20, 20, 20, 20});
    gradientDrawable.setColor(Color.RED);
    return gradientDrawable;
}

LinearLayout layout = new LinearLayout(this);
layout.setBackground(getDrawableWithRadius());

PHP append one array to another (not array_push or +)

For big array, is better to concatenate without array_merge, for avoid a memory copy.

$array1 = array_fill(0,50000,'aa');
$array2 = array_fill(0,100,'bb');

// Test 1 (array_merge)
$start = microtime(true);
$r1 = array_merge($array1, $array2);
echo sprintf("Test 1: %.06f\n", microtime(true) - $start);

// Test2 (avoid copy)
$start = microtime(true);
foreach ($array2 as $v) {
    $array1[] = $v;
}
echo sprintf("Test 2: %.06f\n", microtime(true) - $start);


// Test 1: 0.004963
// Test 2: 0.000038

How to select into a variable in PL/SQL when the result might be null?

You can simply handle the NO_DATA_FOUND exception by setting your variable to NULL. This way, only one query is required.

    v_column my_table.column%TYPE;

BEGIN

    BEGIN
      select column into v_column from my_table where ...;
    EXCEPTION
      WHEN NO_DATA_FOUND THEN
        v_column := NULL;
    END;

    ... use v_column here
END;

A keyboard shortcut to comment/uncomment the select text in Android Studio

if you are findind keyboard shortcuts for Fix doc comment like this:

/**
 * ...
 */

you can do it by useing Live Template(setting - editor - Live Templates - add)

/**
 * $comment$
 */

How to check whether a string is a valid HTTP URL?

All the answers here either allow URLs with other schemes (e.g., file://, ftp://) or reject human-readable URLs that don't start with http:// or https:// (e.g., www.google.com) which is not good when dealing with user inputs.

Here's how I do it:

public static bool ValidHttpURL(string s, out Uri resultURI)
{
    if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase))
        s = "http://" + s;

    if (Uri.TryCreate(s, UriKind.Absolute, out resultURI))
        return (resultURI.Scheme == Uri.UriSchemeHttp || 
                resultURI.Scheme == Uri.UriSchemeHttps);

    return false;
}

Usage:

string[] inputs = new[] {
                          "https://www.google.com",
                          "http://www.google.com",
                          "www.google.com",
                          "google.com",
                          "javascript:alert('Hack me!')"
                        };
foreach (string s in inputs)
{
    Uri uriResult;
    bool result = ValidHttpURL(s, out uriResult);
    Console.WriteLine(result + "\t" + uriResult?.AbsoluteUri);
}

Output:

True    https://www.google.com/
True    http://www.google.com/
True    http://www.google.com/
True    http://google.com/
False

What is the difference between function and procedure in PL/SQL?

  1. we can call a stored procedure inside stored Procedure,Function within function ,StoredProcedure within function but we can not call function within stored procedure.
  2. we can call function inside select statement.
  3. We can return value from function without passing output parameter as a parameter to the stored procedure.

This is what the difference i found. Please let me know if any .

How to include vars file in a vars file with ansible?

Unfortunately, vars files do not have include statements.

You can either put all the vars into the definitions dictionary, or add the variables as another dictionary in the same file.

If you don't want to have them in the same file, you can include them at the playbook level by adding the vars file at the start of the play:

---
- hosts: myhosts

  vars_files:
    - default_step.yml

or in a task:

---
- hosts: myhosts

  tasks:
    - name: include default step variables
      include_vars: default_step.yml

MySQL - Get row number on select

You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).

SELECT 0 INTO @x;

SELECT itemID, 
       COUNT(*) AS ordercount, 
       (@x:=@x+1) AS rownumber 
FROM orders 
GROUP BY itemID 
ORDER BY ordercount DESC; 

Placeholder in UITextView

This thread has had plenty of answers, but here's the version I prefer.

It extends the existing UITextView class so is easily reuseable, and it doesn't intercept the events like textViewDidChange (which might break user's code, if they were already intercepting these events elsewhere).

Using my code (shown below), you can easily add a placeholder to any of your UITextViews like this:

self.textViewComments.placeholder = @"(Enter some comments here.)";

When you set this new placeholder value, it quietly adds a UILabel on top of your UITextView, then hide/shows it as necessary:

enter image description here

Okay, to make these changes, add a "UITextViewHelper.h" file containing this code:

//  UITextViewHelper.h
//  Created by Michael Gledhill on 13/02/15.

#import <Foundation/Foundation.h>

@interface UITextView (UITextViewHelper)

@property (nonatomic, strong) NSString* placeholder;
@property (nonatomic, strong) UILabel* placeholderLabel;
@property (nonatomic, strong) NSString* textValue;

-(void)checkIfNeedToDisplayPlaceholder;

@end

...and a UITextViewHelper.m file containing this:

//  UITextViewHelper.m
//  Created by Michael Gledhill on 13/02/15.
//
//  This UITextView category allows us to easily display a PlaceHolder string in our UITextView.
//  The downside is that, your code needs to set the "textValue" rather than the "text" value to safely set the UITextView's text.
//
#import "UITextViewHelper.h"
#import <objc/runtime.h>

@implementation UITextView (UITextViewHelper)

#define UI_PLACEHOLDER_TEXT_COLOR [UIColor colorWithRed:170.0/255.0 green:170.0/255.0 blue:170.0/255.0 alpha:1.0]

@dynamic placeholder;
@dynamic placeholderLabel;
@dynamic textValue;

-(void)setTextValue:(NSString *)textValue
{
    //  Change the text of our UITextView, and check whether we need to display the placeholder.
    self.text = textValue;
    [self checkIfNeedToDisplayPlaceholder];
}
-(NSString*)textValue
{
    return self.text;
}

-(void)checkIfNeedToDisplayPlaceholder
{
    //  If our UITextView is empty, display our Placeholder label (if we have one)
    if (self.placeholderLabel == nil)
        return;

    self.placeholderLabel.hidden = (![self.text isEqualToString:@""]);
}

-(void)onTap
{
    //  When the user taps in our UITextView, we'll see if we need to remove the placeholder text.
    [self checkIfNeedToDisplayPlaceholder];

    //  Make the onscreen keyboard appear.
    [self becomeFirstResponder];
}

-(void)keyPressed:(NSNotification*)notification
{
    //  The user has just typed a character in our UITextView (or pressed the delete key).
    //  Do we need to display our Placeholder label ?
   [self checkIfNeedToDisplayPlaceholder];
}

#pragma mark - Add a "placeHolder" string to the UITextView class

NSString const *kKeyPlaceHolder = @"kKeyPlaceHolder";
-(void)setPlaceholder:(NSString *)_placeholder
{
    //  Sets our "placeholder" text string, creates a new UILabel to contain it, and modifies our UITextView to cope with
    //  showing/hiding the UILabel when needed.
    objc_setAssociatedObject(self, &kKeyPlaceHolder, (id)_placeholder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    self.placeholderLabel = [[UILabel alloc] initWithFrame:self.frame];
    self.placeholderLabel.numberOfLines = 1;
    self.placeholderLabel.text = _placeholder;
    self.placeholderLabel.textColor = UI_PLACEHOLDER_TEXT_COLOR;
    self.placeholderLabel.backgroundColor = [UIColor clearColor];
    self.placeholderLabel.userInteractionEnabled = true;
    self.placeholderLabel.font = self.font;
    [self addSubview:self.placeholderLabel];

    [self.placeholderLabel sizeToFit];

    //  Whenever the user taps within the UITextView, we'll give the textview the focus, and hide the placeholder if necessary.
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap)]];

    //  Whenever the user types something in the UITextView, we'll see if we need to hide/show the placeholder label.
    [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(keyPressed:) name:UITextViewTextDidChangeNotification object:nil];

    [self checkIfNeedToDisplayPlaceholder];
}
-(NSString*)placeholder
{
    //  Returns our "placeholder" text string
    return objc_getAssociatedObject(self, &kKeyPlaceHolder);
}

#pragma mark - Add a "UILabel" to this UITextView class

NSString const *kKeyLabel = @"kKeyLabel";
-(void)setPlaceholderLabel:(UILabel *)placeholderLabel
{
    //  Stores our new UILabel (which contains our placeholder string)
    objc_setAssociatedObject(self, &kKeyLabel, (id)placeholderLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(keyPressed:) name:UITextViewTextDidChangeNotification object:nil];

    [self checkIfNeedToDisplayPlaceholder];
}
-(UILabel*)placeholderLabel
{
    //  Returns our new UILabel
    return objc_getAssociatedObject(self, &kKeyLabel);
}
@end

Yup, it's a lot of code, but once you've added it to your project and included the .h file...

#import "UITextViewHelper.h"

...you can easily use placeholders in UITextViews.

There's one gotcha though.

If you do this:

self.textViewComments.placeholder = @"(Enter some comments here.)";
self.textViewComments.text = @"Ooooh, hello there";

...the placeholder will appear on top of the text. When you set the text value, none of the regular notifications gets called, so I couldn't work out how to call my function to decide whether to show/hide the placeholder.

The solution is to set the textValue rather than text:

self.textViewComments.placeholder = @"(Enter some comments here.)";
self.textViewComments.textValue = @"Ooooh, hello there";

Alternatively, you can set the text value, then call checkIfNeedToDisplayPlaceholder.

self.textViewComments.text = @"Ooooh, hello there";
[self.textViewComments checkIfNeedToDisplayPlaceholder];

I like solutions like this, as they "fill the gap" between what Apple provides us with, and what we (as developers) actually need in our apps. You write this code once, add it to your library of "helper" .m/.h files, and, over time, the SDK actually starts becoming less frustrating.

(I wrote a similar helper for adding a "clear" button to my UITextViews, another thing which annoyingly exists in UITextField but not in UITextView...)

How do I check if there are duplicates in a flat list?

Another way of doing this succinctly is with Counter.

To just determine if there are any duplicates in the original list:

from collections import Counter

def has_dupes(l):
    # second element of the tuple has number of repetitions
    return Counter(l).most_common()[0][1] > 1

Or to get a list of items that have duplicates:

def get_dupes(l):
    return [k for k, v in Counter(l).items() if v > 1]

What is the "right" JSON date format?

I believe that the best format for universal interoperability is not the ISO-8601 string, but rather the format used by EJSON:

{ "myDateField": { "$date" : <ms-since-epoch> } }

As described here: https://docs.meteor.com/api/ejson.html

Benefits

  1. Parsing performance: If you store dates as ISO-8601 strings, this is great if you are expecting a date value under that particular field, but if you have a system which must determine value types without context, you're parsing every string for a date format.
  2. No Need for Date Validation: You need not worry about validation and verification of the date. Even if a string matches ISO-8601 format, it may not be a real date; this can never happen with an EJSON date.
  3. Unambiguous Type Declaration: as far as generic data systems go, if you wanted to store an ISO string as a string in one case, and a real system date in another, generic systems adopting the ISO-8601 string format will not allow this, mechanically (without escape tricks or similar awful solutions).

Conclusion

I understand that a human-readable format (ISO-8601 string) is helpful and more convenient for 80% of use cases, and indeed no-one should ever be told not to store their dates as ISO-8601 strings if that's what their applications understand, but for a universally accepted transport format which should guarantee certain values to for sure be dates, how can we allow for ambiguity and need for so much validation?

jQuery changing css class to div

An HTML element like div can have more than one classes. Let say div is assigned two styles using addClass method. If style1 has 3 properties like font-size, weight and color, and style2 has 4 properties like font-size, weight, color and background-color, the resultant effective properties set (style), i think, will have 4 properties i.e. union of all style sets. Common properties, in our case, color,font-size, weight, will have one occuerance with latest values. If div is assigned style1 first and style2 second, the common prpoerties will be overwritten by style2 values.

Further, I have written a post at Using JQuery to Apply,Remove and Manage Styles, I hope it will help you

Regards Awais

ASP.NET MVC: Custom Validation by DataAnnotation

A bit late to answer, but for who is searching. You can easily do this by using an extra property with the data annotation:

public string foo { get; set; }
public string bar { get; set; }

[MinLength(20, ErrorMessage = "too short")]
public string foobar 
{ 
    get
    {
        return foo + bar;
    }
}

That's all that is too it really. If you really want to display in a specific place the validation error as well, you can add this in your view:

@Html.ValidationMessage("foobar", "your combined text is too short")

doing this in the view can come in handy if you want to do localization.

Hope this helps!

HTTP Basic: Access denied fatal: Authentication failed

When it asks for username and password. Just add gitlab user name and password for clonning. For the box to pop up asking credentials, do the following:

go to "control panel"-> user accounts-> manage credentials->windows credentials->git:https://[email protected]>click on down arrow-> then click remove.

Hope this helps!

:touch CSS pseudo-class or something similar?

Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color is the fastest to respond (subjective).

Add the following to your body and your links will have a tap effect.

body {
    -webkit-tap-highlight-color: #ccc;
}

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

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

You should set this for setAuthorState method

class ManageAuthorPage extends Component {

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

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

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

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

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

Another alternative based on arrow function:

class ManageAuthorPage extends Component {

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

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

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

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

How do I update a model value in JavaScript in a Razor view?

You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.

It would look something like this:

function updatePostID(val, comment)
{

    var args = {};
    args.PostID = val;
    args.Comment = comment;

    $.ajax({
     type: "POST",
     url: controllerActionMethodUrlHere,
     contentType: "application/json; charset=utf-8",
     data: args,
     dataType: "json",
     success: function(msg) 
     {
        // Something afterwards here

     }
    });

}

Update built-in vim on Mac OS X

Like Eric, I used homebrew, but I used the default recipe. So:

brew install mercurial
brew install vim

And after restarting the terminal homebrew's vim should be the default. If not, you should update your $PATH so that /usr/local/bin is before /usr/bin. E.g. add the following to your .profile:

export PATH=/usr/local/bin:$PATH

How can I exclude $(this) from a jQuery selector?

You should use the "siblings()" method, and prevent from running the ".content a" selector over and over again just for applying that effect:

HTML

<div class="content">
    <a href="#">A</a>
</div>
<div class="content">
    <a href="#">B</a>
</div>
<div class="content">
    <a href="#">C</a>
</div>

CSS

.content {
    background-color:red;
    margin:10px;
}
.content.other {
    background-color:yellow;
}

Javascript

$(".content a").click(function() {
  var current = $(this).parent();
  current.removeClass('other')
    .siblings()
    .addClass('other');
});

See here: http://jsfiddle.net/3bzLV/1/

How to send a header using a HTTP request through a curl call?

In PHP:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('HeaderName:HeaderValue'));

or you can set multiple:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('HeaderName:HeaderValue', 'HeaderName2:HeaderValue2'));

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

Changing website favicon dynamically

There is a single line solution for those who use jQuery:

$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');

AWS EFS vs EBS vs S3 (differences & when to use?)

In simple words

Amazon EBS provides block level storage .

Amazon EFS provides network-attached shared file storage.

Amazon S3 provides object storage .

How to create RecyclerView with multiple view type?

Create different ViewHolder for different layout

enter image description here
RecyclerView can have any number of viewholders you want but for better readability lets see how to create one with two ViewHolders.

It can be done in three simple steps

  1. Override public int getItemViewType(int position)
  2. Return different ViewHolders based on the ViewType in onCreateViewHolder() method
  3. Populate View based on the itemViewType in onBindViewHolder() method

Here is a small code snippet

public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

   private static final int LAYOUT_ONE= 0;
   private static final int LAYOUT_TWO= 1;

   @Override
   public int getItemViewType(int position)
   {
      if(position==0)
        return LAYOUT_ONE;
      else
        return LAYOUT_TWO;
   }

   @Override
   public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

      View view =null;
      RecyclerView.ViewHolder viewHolder = null;

      if(viewType==LAYOUT_ONE)
      {
          view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
          viewHolder = new ViewHolderOne(view);
      }
      else
      {
          view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
          viewHolder= new ViewHolderTwo(view);
      }

      return viewHolder;
   }

   @Override
   public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

      if(holder.getItemViewType()== LAYOUT_ONE)
      {
            // Typecast Viewholder 
            // Set Viewholder properties 
            // Add any click listener if any 
      }
      else {

        ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
        vaultItemHolder.name.setText(displayText);
        vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
            .......
           }
         });

       }

   }

  //****************  VIEW HOLDER 1 ******************//

   public class ViewHolderOne extends RecyclerView.ViewHolder {

      public TextView name;

      public ViewHolderOne(View itemView) {
         super(itemView);
         name = (TextView)itemView.findViewById(R.id.displayName);
     }
   }


   //****************  VIEW HOLDER 2 ******************//

   public class ViewHolderTwo extends RecyclerView.ViewHolder{

      public ViewHolderTwo(View itemView) {
         super(itemView);

        ..... Do something
      }
   }
}

getItemViewType(int position) is the key

In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.

Lets see one example to prove my point. If you want to show two layout at alternate positions do this

@Override
public int getItemViewType(int position)
{
   if(position%2==0)       // Even position 
     return LAYOUT_ONE;
   else                   // Odd position 
     return LAYOUT_TWO;
}

Relevant Links:

Check out the project where I have implemented this

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

In Python, how do I iterate over a dictionary in sorted key order?

Haven't tested this very extensively, but works in Python 2.5.2.

>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
>>> it.next()
('a', 2222)
>>> it.next()
('h', 15)
>>> it.next()
('x', 2)
>>>

If you are used to doing for key, value in d.iteritems(): ... instead of iterators, this will still work with the solution above

>>> d = {"x":2, "h":15, "a":2222}
>>> for key, value in sorted(d.iteritems()):
>>>     print(key, value)
('a', 2222)
('h', 15)
('x', 2)
>>>

With Python 3.x, use d.items() instead of d.iteritems() to return an iterator.