Programs & Examples On #Affinetransform

An affine transform is a special 3x3 matrix used to apply translation, rotation, shearing or skew, and scaling to coordinate systems in two dimensional graphic contexts.

UIView Infinite 360 degree rotation animation?

There are following different ways to perform 360 degree animation with UIView.

Using CABasicAnimation

var rotationAnimation = CABasicAnimation()
rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: (Double.pi))
rotationAnimation.duration = 1.0
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = 100.0
view.layer.add(rotationAnimation, forKey: "rotationAnimation")


Here is an extension functions for UIView that handles start & stop rotation operations:

extension UIView {

    // Start rotation
    func startRotation() {
        let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.fromValue = 0
        rotation.toValue = NSNumber(value: Double.pi)
        rotation.duration = 1.0
        rotation.isCumulative = true
        rotation.repeatCount = FLT_MAX
        self.layer.add(rotation, forKey: "rotationAnimation")
    }

    // Stop rotation
    func stopRotation() {
        self.layer.removeAnimation(forKey: "rotationAnimation")
    }
}


Now using, UIView.animation closure:

UIView.animate(withDuration: 0.5, animations: { 
      view.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi)) 
}) { (isAnimationComplete) in
    // Animation completed 
}

Java: Rotating Images

public static BufferedImage rotateCw( BufferedImage img )
{
    int         width  = img.getWidth();
    int         height = img.getHeight();
    BufferedImage   newImage = new BufferedImage( height, width, img.getType() );

    for( int i=0 ; i < width ; i++ )
        for( int j=0 ; j < height ; j++ )
            newImage.setRGB( height-1-j, i, img.getRGB(i,j) );

    return newImage;
}

from https://coderanch.com/t/485958/java/Rotating-buffered-image

How to Rotate a UIImage 90 degrees?

Swift 3 UIImage extension:

func fixOrientation() -> UIImage {

    // No-op if the orientation is already correct
    if ( self.imageOrientation == .up ) {
        return self;
    }

    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    var transform: CGAffineTransform = .identity

    if ( self.imageOrientation == .down || self.imageOrientation == .downMirrored ) {
        transform = transform.translatedBy(x: self.size.width, y: self.size.height)
        transform = transform.rotated(by: .pi)
    }

    if ( self.imageOrientation == .left || self.imageOrientation == .leftMirrored ) {
        transform = transform.translatedBy(x: self.size.width, y: 0)
        transform = transform.rotated(by: .pi/2)
    }

    if ( self.imageOrientation == .right || self.imageOrientation == .rightMirrored ) {
        transform = transform.translatedBy(x: 0, y: self.size.height);
        transform = transform.rotated(by: -.pi/2);
    }

    if ( self.imageOrientation == .upMirrored || self.imageOrientation == .downMirrored ) {
        transform = transform.translatedBy(x: self.size.width, y: 0)
        transform = transform.scaledBy(x: -1, y: 1)
    }

    if ( self.imageOrientation == .leftMirrored || self.imageOrientation == .rightMirrored ) {
        transform = transform.translatedBy(x: self.size.height, y: 0);
        transform = transform.scaledBy(x: -1, y: 1);
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    let ctx: CGContext = CGContext(data: nil, width: Int(self.size.width), height: Int(self.size.height),
                                   bitsPerComponent: self.cgImage!.bitsPerComponent, bytesPerRow: 0,
                                   space: self.cgImage!.colorSpace!,
                                   bitmapInfo: self.cgImage!.bitmapInfo.rawValue)!;

    ctx.concatenate(transform)

    if ( self.imageOrientation == .left ||
        self.imageOrientation == .leftMirrored ||
        self.imageOrientation == .right ||
        self.imageOrientation == .rightMirrored ) {
        ctx.draw(self.cgImage!, in: CGRect(x: 0.0,y: 0.0,width: self.size.height,height: self.size.width))
    } else {
        ctx.draw(self.cgImage!, in: CGRect(x: 0.0,y: 0.0,width: self.size.width,height: self.size.height))
    }

    // And now we just create a new UIImage from the drawing context and return it
    return UIImage(cgImage: ctx.makeImage()!)
}

How to read a CSV file into a .NET Datatable

Can't resist adding my own spin to this. This is so much better and more compact than what I've used in the past.

This solution:

  • Does not depend on a database driver or 3rd party library.
  • Will not fail on duplicate column names
  • Handles commas in the data
  • Handles any delimiter, not just commas (although that is the default)

Here's what I came up with:

  Public Function ToDataTable(FileName As String, Optional Delimiter As String = ",") As DataTable
    ToDataTable = New DataTable
    Using TextFieldParser As New Microsoft.VisualBasic.FileIO.TextFieldParser(FileName) With
      {.HasFieldsEnclosedInQuotes = True, .TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited, .TrimWhiteSpace = True}
      With TextFieldParser
        .SetDelimiters({Delimiter})
        .ReadFields.ToList.Unique.ForEach(Sub(x) ToDataTable.Columns.Add(x))
        ToDataTable.Columns.Cast(Of DataColumn).ToList.ForEach(Sub(x) x.AllowDBNull = True)
        Do Until .EndOfData
          ToDataTable.Rows.Add(.ReadFields.Select(Function(x) Text.BlankToNothing(x)).ToArray)
        Loop
      End With
    End Using
  End Function

It depends on an extension method (Unique) to handle duplicate column names to be found as my answer in How to append unique numbers to a list of strings

And here's the BlankToNothing helper function:

  Public Function BlankToNothing(ByVal Value As String) As Object 
    If String.IsNullOrEmpty(Value) Then Return Nothing
    Return Value
  End Function

Converting from IEnumerable to List

If you're using an implementation of System.Collections.IEnumerable you can do like following to convert it to a List. The following uses Enumerable.Cast method to convert IEnumberable to a Generic List.

//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");

List<string> provinces = _provinces.Cast<string>().ToList();

If you're using Generic version IEnumerable<T>, The conversion is straight forward. Since both are generics, you can do like below,

IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();

But if the IEnumerable is null, when you try to convert it to a List, you'll get ArgumentNullException saying Value cannot be null.

IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();

enter image description here

Therefore as mentioned in the other answer, remember to do a null check before converting it to a List.

How to move all files including hidden files into parent directory via *

By using the find command in conjunction with the mv command, you can prevent the mv command from trying to move directories (e.g. .. and .) and subdirectories. Here's one option:

find /path/subfolder -maxdepth 1 -type f -name '*' -exec mv -n {} /path \;

There are problems with some of the other answers provided. For example, each of the following will try to move subdirectories from the source path:

1) mv /path/subfolder/* /path/ ; mv /path/subfolder/.* /path/
2) mv /path/subfolder/{.,}* /path/ 
3) mv /source/path/{.[!.],}* /destination/path

Also, 2) includes the . and .. files and 3) misses files like ..foobar, ...barfoo, etc.

You could use, mv /source/path/{.[!.],..?,}* /destination/path, which would include the files missed by 3), but it would still try to move subdirectories. Using the find command with the mv command as I describe above eliminates all these problems.

Creating virtual directories in IIS express

In VS2013 I did this in the following steps:

1.Right-click the web application project and hit Properties

2.View the "Web" tab of the Properties page

3.Under Servers, with "IIS Express" being the default choice of the dropdown, in the "Project Url" change the url using the port number to one that suits you. For example I deleted the port number and added "/MVCDemo4" after the localhost.

4.Click the "Create Virtual Directory" button.

5.Run your project and the new url will be used

How to SELECT a dropdown list item by value programmatically

Ian Boyd (above) had a great answer -- Add this to Ian Boyd's class "WebExtensions" to select an item in a dropdownlist based on text:

/// <summary>
/// Selects the item in the list control that contains the specified text, if it exists.
/// </summary>
/// <param name="dropDownList"></param>
/// <param name="selectedText">The text of the item in the list control to select</param>
/// <returns>Returns true if the value exists in the list control, false otherwise</returns>
public static Boolean SetSelectedText(this DropDownList dropDownList, String selectedText)
{
    ListItem selectedListItem = dropDownList.Items.FindByText(selectedText);
    if (selectedListItem != null)
    {
        selectedListItem.Selected = true;
        return true;
    }
    else
        return false;
}

To call it:

WebExtensions.SetSelectedText(MyDropDownList, "MyValue");

Oracle - Insert New Row with Auto Incremental ID

SQL trigger for automatic date generation in oracle table:

CREATE OR REPLACE TRIGGER name_of_trigger

BEFORE INSERT

ON table_name

REFERENCING NEW AS NEW

FOR EACH ROW

BEGIN

SELECT sysdate INTO :NEW.column_name FROM dual;

END;

/

Difference between .keystore file and .jks file

You are confused on this.

A keystore is a container of certificates, private keys etc.

There are specifications of what should be the format of this keystore and the predominant is the #PKCS12

JKS is Java's keystore implementation. There is also BKS etc.

These are all keystore types.

So to answer your question:

difference between .keystore files and .jks files

There is none. JKS are keystore files. There is difference though between keystore types. E.g. JKS vs #PKCS12

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

As an alternative answer, there's a command line to invoke directly the Control Panel, which is javaws -viewer, should work for both openJDK and Oracle's JDK (thanks @Nasser for checking the availability in Oracle's JDK)

Same caution to run as the user you need to access permissions with applies.

How do you do relative time in Rails?

Something like this would work.

def relative_time(start_time)
  diff_seconds = Time.now - start_time
  case diff_seconds
    when 0 .. 59
      puts "#{diff_seconds} seconds ago"
    when 60 .. (3600-1)
      puts "#{diff_seconds/60} minutes ago"
    when 3600 .. (3600*24-1)
      puts "#{diff_seconds/3600} hours ago"
    when (3600*24) .. (3600*24*30) 
      puts "#{diff_seconds/(3600*24)} days ago"
    else
      puts start_time.strftime("%m/%d/%Y")
  end
end

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

There was no year 0000 and there is no month 00 or day 00. I suggest you try

0001-01-01 00:00:00

While a year 0 has been defined in some standards, it is more likely to be confusing than useful IMHO.

Kill all processes for a given user

What about iterating on the /proc virtual file system ? http://linux.die.net/man/5/proc ?

How to read multiple Integer values from a single line of input in Java?

i know it's old discuss :) i tested below code it's worked

`String day = "";
 day = sc.next();
 days[i] = Integer.parseInt(day);`

How do I load a file from resource folder?

To read the files from src/resources folder then try this :

DataSource fds = new FileDataSource(getFileHandle("images/sample.jpeg"));

public static File getFileHandle(String fileName){
       return new File(YourClassName.class.getClassLoader().getResource(fileName).getFile());
}

in case of non static reference:

return new File(getClass().getClassLoader().getResource(fileName).getFile());

Spring Boot Program cannot find main class

Have a look under "Run -> Run Configurations..." in Eclipse. You should delete the new one which you created by mistake, you should still have the existing one.

I suspect it has created a new run configuration for the "Run as Maven Test" and you are now always starting this one.

How do I do an insert with DATETIME now inside of SQL server mgmt studioÜ

Just use GETDATE() or GETUTCDATE() (if you want to get the "universal" UTC time, instead of your local server's time-zone related time).

INSERT INTO [Business]
           ([IsDeleted]
           ,[FirstName]
           ,[LastName]
           ,[LastUpdated]
           ,[LastUpdatedBy])
     VALUES
           (0, 'Joe', 'Thomas', 
           GETDATE(),  <LastUpdatedBy, nvarchar(50),>)

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

AngularJS. How to call controller function from outside of controller component

It may be worth considering if having your menu without any associated scope is the right way to go. Its not really the angular way.

But, if it is the way you need to go, then you can do it by adding the functions to $rootScope and then within those functions using $broadcast to send events. your controller then uses $on to listen for those events.

Another thing to consider if you do end up having your menu without a scope is that if you have multiple routes, then all of your controllers will have to have their own upate and get functions. (this is assuming you have multiple controllers)

What is the purpose and use of **kwargs?

You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

>>> def print_keyword_args(**kwargs):
...     # kwargs is a dict of the keyword args passed to the function
...     for key, value in kwargs.iteritems():
...         print "%s = %s" % (key, value)
... 
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe

You can also use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:

>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith

The Python Tutorial contains a good explanation of how it works, along with some nice examples.

<--Update-->

For people using Python 3, instead of iteritems(), use items()

Check if a string within a list contains a specific string with Linq

LINQ Any() would do the job:

bool contains = myList.Any(s => s.Contains(pattern));

Any(), MSDN:

Determines whether any element of a sequence satisfies a condition

How to read data from a zip file without having to unzip the entire file

With .Net Framework 4.5 (using ZipArchive):

using (ZipArchive zip = ZipFile.Open(zipfile, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        if(entry.Name == "myfile")
            entry.ExtractToFile("myfile");

Find "myfile" in zipfile and extract it.

IIS7 Permissions Overview - ApplicationPoolIdentity

Remember to use the server's local name, not the domain name, when resolving the name

IIS AppPool\DefaultAppPool

(just a reminder because this tripped me up for a bit):enter image description here

How to use *ngIf else?

<div *ngIf="show; else elseBlock">Text to show</div>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>

AssertNull should be used or AssertNotNull

assertNotNull asserts that the object is not null. If it is null the test fails, so you want that.

How do I prevent 'git diff' from using a pager?

Just follow below instructions.

  1. Just type vi ~/.gitconfig in your terminal.
  2. Paste LESS="-F -X $LESS" line.
  3. Press :wq and enter.
  4. Restart your terminal.

No appenders could be found for logger(log4j)?

This Short introduction to log4j guide is a little bit old but still valid.

That guide will give you some information about how to use loggers and appenders.


Just to get you going you have two simple approaches you can take.

First one is to just add this line to your main method:

BasicConfigurator.configure();

Second approach is to add this standard log4j.properties (taken from the above mentioned guide) file to your classpath:

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Why does git status show branch is up-to-date when changes exist upstream?

"origin/master" refers to the reference poiting to the HEAD commit of branch "origin/master". A reference is a human-friendly alias name to a Git object, typically a commit object. "origin/master" reference only gets updated when you git push to your remote (http://git-scm.com/book/en/v2/Git-Internals-Git-References#Remotes).

From within the root of your project, run:

cat .git/refs/remotes/origin/master

Compare the displayed commit ID with:

cat .git/refs/heads/master

They should be the same, and that's why Git says master is up-to-date with origin/master.

When you run

git fetch origin master

That retrieves new Git objects locally under .git/objects folder. And Git updates .git/FETCH_HEAD so that now, it points to the latest commit of the fetched branch.

So to see the differences between your current local branch, and the branch fetched from upstream, you can run

git diff HEAD FETCH_HEAD

RegEx to exclude a specific string constant

Try this regular expression:

^(.{0,2}|([^A]..|A[^B].|AB[^C])|.{4,})$

It describes three cases:

  1. less than three arbitrary character
  2. exactly three characters, while either
    • the first is not A, or
    • the first is A but the second is not B, or
    • the first is A, the second B but the third is not C
  3. more than three arbitrary characters

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;
    title[title.length]=titleValue;
    names[names.length]=actorValue;
    tickets[tickets.length]=ticketsValue;
  }

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  }
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  }
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  }
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup
}

Here's a jsfiddle for you to play around.

How do write IF ELSE statement in a MySQL query

according to the mySQL reference manual this the syntax of using if and else statement :

IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF

So regarding your query :

x = IF((action=2)&&(state=0),1,2);

or you can use

IF ((action=2)&&(state=0)) then 
state = 1;
ELSE 
state = 2;
END IF;

There is good example in this link : http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

How do I check in SQLite whether a table exists?

Using a simple SELECT query is - in my opinion - quite reliable. Most of all it can check table existence in many different database types (SQLite / MySQL).

SELECT 1 FROM table;

It makes sense when you can use other reliable mechanism for determining if the query succeeded (for example, you query a database via QSqlQuery in Qt).

In Perl, how do I create a hash whose keys come from a given array?

You could also use Perl6::Junction.

use Perl6::Junction qw'any';

my @arr = ( 1, 2, 3 );

if( any(@arr) == 1 ){ ... }

Do not want scientific notation on plot axis

You can use format or formatC to, ahem, format your axis labels.

For whole numbers, try

x <- 10 ^ (1:10)
format(x, scientific = FALSE)
formatC(x, digits = 0, format = "f")

If the numbers are convertable to actual integers (i.e., not too big), you can also use

formatC(x, format = "d")

How you get the labels onto your axis depends upon the plotting system that you are using.

Copy files from one directory into an existing directory

If you want to copy something from one directory into the current directory, do this:

cp dir1/* .

This assumes you're not trying to copy hidden files.

How to crop a CvMat in OpenCV?

OpenCV has region of interest functions which you may find useful. If you are using the cv::Mat then you could use something like the following.

// You mention that you start with a CVMat* imagesource
CVMat * imagesource;

// Transform it into the C++ cv::Mat format
cv::Mat image(imagesource); 

// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);

// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedImage = image(myROI);

Documentation for extracting sub image

How to find sitemap.xml path on websites?

Use Google Search Operators to find it for you

search google with the below code..

inurl:domain.com filetype:xml click on this to view sitemap search example

change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)

Should IBOutlets be strong or weak under ARC?

While the documentation recommends using weak on properties for subviews, since iOS 6 it seems to be fine to use strong (the default ownership qualifier) instead. That's caused by the change in UIViewController that views are not unloaded anymore.

  • Before iOS 6, if you kept strong links to subviews of the controller's view around, if the view controller's main view got unloaded, those would hold onto the subviews as long as the view controller is around.
  • Since iOS 6, views are not unloaded anymore, but loaded once and then stick around as long as their controller is there. So strong properties won't matter. They also won't create strong reference cycles, since they point down the strong reference graph.

That said, I am torn between using

@property (nonatomic, weak) IBOutlet UIButton *button;

and

@property (nonatomic) IBOutlet UIButton *button;

in iOS 6 and after:

  • Using weak clearly states that the controller doesn't want ownership of the button.

  • But omitting weak doesn't hurt in iOS 6 without view unloading, and is shorter. Some may point out that is also faster, but I have yet to encounter an app that is too slow because of weak IBOutlets.

  • Not using weak may be perceived as an error.

Bottom line: Since iOS 6 we can't get this wrong anymore as long as we don't use view unloading. Time to party. ;)

Submit form with Enter key without submit button?

Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none; on a submit button in the form.

How can I specify a local gem in my Gemfile?

If you want the branch too:

gem 'foo', path: "point/to/your/path", branch: "branch-name"

add controls vertically instead of horizontally using flow layout

I hope what you are trying to achieve is like this. For this please use Box layout.

package com.kcing.kailas.sample.client;

import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

public class Testing extends JFrame {

    private JPanel jContentPane = null;

    public Testing() {
        super();
        initialize();
    }

    private void initialize() {
        this.setSize(300, 200);
        this.setContentPane(getJContentPane());
        this.setTitle("JFrame");
    }

    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(null);

            JPanel panel = new JPanel();

            panel.setBounds(61, 11, 81, 140);
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            jContentPane.add(panel);

            JCheckBox c1 = new JCheckBox("Check1");
            panel.add(c1);
            c1 = new JCheckBox("Check2");
            panel.add(c1);
            c1 = new JCheckBox("Check3");
            panel.add(c1);
            c1 = new JCheckBox("Check4");
            panel.add(c1);
        }
        return jContentPane;
    }

    public static void main(String[] args) throws Exception {
        Testing frame = new Testing();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
}

How to break line in JavaScript?

Here you are ;-)

<script type="text/javascript">
    alert("Hello there.\nI am on a second line ;-)")
</script>

Change background colour for Visual Studio

Tools -> Options -> Under the Environment section there are Fonts & Colors, change the Item Background.

Get current value selected in dropdown using jQuery

You can also use :checked

$("#myselect option:checked").val(); //to get value

or as said in other answers simply

$("#myselect").val(); //to get value

and

$("#myselect option:checked").text(); //to get text

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

I got the same problem with a project written in 1.7 and tried to execute in 1.6.

My solution in Eclipse:

  • Right click on your Project Properties -> Java Build Path -> Libraries

  • Select your JRE System Library and click Edit on the right, and choose the target JRE.

  • Now go to Java Compiler on the left, and change the Compiler compliance level to your target.

That worked for me.

How to assign a heredoc value to a variable in Bash?

Branching off Neil's answer, you often don't need a var at all, you can use a function in much the same way as a variable and it's much easier to read than the inline or read-based solutions.

$ complex_message() {
  cat <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF
}

$ echo "This is a $(complex_message)"
This is a abc'asdf"
$(dont-execute-this)
foo"bar"''

Python: How would you save a simple settings/config file?

Try using ReadSettings:

from readsettings import ReadSettings
data = ReadSettings("settings.json") # Load or create any json, yml, yaml or toml file
data["name"] = "value" # Set "name" to "value"
data["name"] # Returns: "value"

gdb: "No symbol table is loaded"

I have the same problem and I followed this Post, it solved my problem.

Follow the following 2 steps:

  1. Make sure the optimization level is -O0
  2. Add -ggdb flag when compiling your program

Good luck!

Execution sequence of Group By, Having and Where clause in SQL Server?

This is the SQL Order of execution of a Query,

enter image description here

You can check order of execution with examples from this article.

For you question below lines might be helpful and directly got from this article.

  1. GROUP BY --> The remaining rows after the WHERE constraints are applied are then grouped based on common values in the column specified in the GROUP BY clause. As a result of the grouping, there will only be as many rows as there are unique values in that column. Implicitly, this means that you should only need to use this when you have aggregate functions in your query.
  1. HAVING --> If the query has a GROUP BY clause, then the constraints in the HAVING clause are then applied to the grouped rows, discard the grouped rows that don't satisfy the constraint. Like the WHERE clause, aliases are also not accessible from this step in most databases.

References:-

Excel "External table is not in the expected format."

I was getting errors with third party and Oledb reading of a XLSX workbook. The issue appears to be a hidden worksheet that causes a error. Unhiding the worksheet enabled the workbook to import.

How to sort by dates excel?

  1. Select the whole column
  2. Right click -> Format cells... -> Number -> Category: Date -> OK
  3. Data -> Text to Columns -> select Delimited -> Next -> in your case selection of Delimiters doesn't matter -> Next -> select Date: DMY -> Finish

Now you should be able to sort by this column either Oldest to Newest or Newest to Oldest

Explanation of <script type = "text/template"> ... </script>

By setting script tag type other than text/javascript, browser will not execute the internal code of script tag. This is called micro template. This concept is widely used in Single page application(aka SPA).

<script type="text/template">I am a Micro template. 
  I am going to make your web page faster.</script>

For micro template, type of the script tag is text/template. It is very well explained by Jquery creator John Resig http://ejohn.org/blog/javascript-micro-templating/

how to declare global variable in SQL Server..?

I like the approach of using a table with a column for each global variable. This way you get autocomplete to aid in coding the retrieval of the variable. The table can be restricted to a single row as outlined here: SQL Server: how to constrain a table to contain a single row?

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

How can I delete all cookies with JavaScript?

On the face of it, it looks okay - if you call eraseCookie() on each cookie that is read from document.cookie, then all of your cookies will be gone.

Try this:

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
  eraseCookie(cookies[i].split("=")[0]);

All of this with the following caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

As an addendum to the previous answers -- there's a workaround I just discovered for if you can't or don't want to add all this boilerplate to your project POM. If you look in the following location:

{Eclipse_folder}/plugins/org.eclipse.m2e.lifecyclemapping.defaults_{m2e_version}

You should find a file called lifecycle-mapping-metadata.xml where you can make the same changes described in the other answers and in M2E plugin execution not covered.

LINQ select one field from list of DTO objects to array

You can select all Sku elements of your myLines list and then convert the result to an array.

string[] mySKUsArray = myLines.Select(x=>x.Sku).ToArray();

Database Diagram Support Objects cannot be Installed ... no valid owner

Enter "SA" instead of "sa" in the owner textbox. This worked for me.

Change Title of Javascript Alert

It's not possible, sorry. If really needed, you could use a jQuery plugin to have a custom alert.

How to work with progress indicator in flutter?

Step 1: Create Dialog

   showAlertDialog(BuildContext context){
      AlertDialog alert=AlertDialog(
        content: new Row(
            children: [
               CircularProgressIndicator(),
               Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
            ],),
      );
      showDialog(barrierDismissible: false,
        context:context,
        builder:(BuildContext context){
          return alert;
        },
      );
    }

Step 2:Call it

showAlertDialog(context);
await firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
Navigator.pop(context);

Example With Dialog and login form

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class DynamicLayout extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new MyWidget();
    }
  }
showAlertDialog(BuildContext context){
  AlertDialog alert=AlertDialog(
    content: new Row(
        children: [
           CircularProgressIndicator(),
           Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
        ],),
  );
  showDialog(barrierDismissible: false,
    context:context,
    builder:(BuildContext context){
      return alert;
    },
  );
}

  class MyWidget extends State<DynamicLayout>{
  Color color = Colors.indigoAccent;
  String title='app';
  GlobalKey<FormState> globalKey=GlobalKey<FormState>();
  String email,password;
  login() async{
   var currentState= globalKey.currentState;
   if(currentState.validate()){
        currentState.save();
        FirebaseAuth firebaseAuth=FirebaseAuth.instance;
        try {
          showAlertDialog(context);
          AuthResult authResult=await firebaseAuth.signInWithEmailAndPassword(
              email: email, password: password);
          FirebaseUser user=authResult.user;
          Navigator.pop(context);
        }catch(e){
          print(e);
        }
   }else{

   }
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar:AppBar(
        title: Text("$title"),
        ) ,
          body: Container(child: Form(
            key: globalKey,
            child: Container(
              padding: EdgeInsets.all(10),
              child: Column(children: <Widget>[
              TextFormField(decoration: InputDecoration(icon: Icon(Icons.email),labelText: 'Email'),
              // ignore: missing_return
              validator:(val){
                if(val.isEmpty)
                  return 'Please Enter Your Email';
              },
              onSaved:(val){
                email=val;
              },
              ),
                TextFormField(decoration: InputDecoration(icon: Icon(Icons.lock),labelText: 'Password'),
             obscureText: true,
                  // ignore: missing_return
                  validator:(val){
                    if(val.isEmpty)
                      return 'Please Enter Your Password';
                  },
                  onSaved:(val){
                    password=val;
                  },
              ),
                RaisedButton(color: Colors.lightBlue,textColor: Colors.white,child: Text('Login'),
                  onPressed:login),
            ],)
              ,),)
         ),
    );
  }
}

enter image description here

How can I remove the outline around hyperlinks images?

You can use the CSS property "outline" and value of "none" on the anchor element.

a {
outline: none;
}

Hope that helps.

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

It not containing the object can happen during normal operations and should be dealt with by the caller return NULL.

If not containing the object indicates a bug by the calling code or internal state then do an assert.

If not containing the object indicates an infrequent event. (Like someone deleted an item from the store while you were checking out the item at the same time.) Then throw an exception.

Call and receive output from Python script in Java?

First I would recommend to use ProcessBuilder ( since 1.5 )
Simple usage is described here
https://stackoverflow.com/a/14483787
For more complex example refer to
http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html

I've encountered problem when launching Python script from Java, script was producing too much output to standard out and everything went bad.

batch file to copy files to another location?

Open Notepad.

Type the following lines into it (obviously replace the folders with your ones)

@echo off
rem you could also remove the line above, because it might help you to see what happens

rem /i option is needed to avoid the batch file asking you whether destination folder is a file or a folder
rem /e option is needed to copy also all folders and subfolders
xcopy "c:\New Folder" "c:\Copy of New Folder" /i /e

Save the file as backup.bat (not .txt)

Double click on the file to run it. It will backup the folder and all its contents files/subfolders.

Now if you want the batch file to be run everytime you login in Windows, you should place it in Windows Startup menu. You find it under: Start > All Program > Startup To place the batch file in there either drag it into the Startup menu or RIGH click on the Windows START button and select Explore, go in Programs > Startup, and copy the batch file into there.

To run the batch file everytime the folder is updated you need an application, it can not be done with just a batch file.

How can one pull the (private) data of one's own Android app?

Here is what worked for me:

adb -d shell "run-as com.example.test cat /data/data/com.example.test/databases/data.db" > data.db

I'm printing the database directly into local file.

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I implemented Joseph Johnson solution and it worked well, I noticed after using this solution sometimes the drawer on the application will not close properly. I added a functionality to remove the listener removeOnGlobalLayoutListener when the user closes the fragment where are edittexts located.

    //when the application uses full screen theme and the keyboard is shown the content not scrollable! 
//with this util it will be scrollable once again
//http://stackoverflow.com/questions/7417123/android-how-to-adjust-layout-in-full-screen-mode-when-softkeyboard-is-visible
public class AndroidBug5497Workaround {


    private static AndroidBug5497Workaround mInstance = null;
    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;
    private ViewTreeObserver.OnGlobalLayoutListener _globalListener;

    // For more information, see https://code.google.com/p/android/issues/detail?id=5497
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.

    public static AndroidBug5497Workaround getInstance (Activity activity) {
        if(mInstance==null)
        {
            synchronized (AndroidBug5497Workaround.class)
            {
                mInstance = new AndroidBug5497Workaround(activity);
            }
        }
        return mInstance;
    }

    private AndroidBug5497Workaround(Activity activity) {
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();

        _globalListener = new ViewTreeObserver.OnGlobalLayoutListener()
        {

            @Override
            public void onGlobalLayout()
            {
                 possiblyResizeChildOfContent();
            }
        };
    }

    public void setListener()
    {
         mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(_globalListener);
    }

    public void removeListener()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mChildOfContent.getViewTreeObserver().removeOnGlobalLayoutListener(_globalListener);
        } else {
            mChildOfContent.getViewTreeObserver().removeGlobalOnLayoutListener(_globalListener);
        }
    }

    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            if (heightDifference > (usableHeightSansKeyboard/4)) {
                // keyboard probably just became visible
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
            } else {
                // keyboard probably just became hidden
                frameLayoutParams.height = usableHeightSansKeyboard;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    } 
}

uses the class where is my edittexts located

@Override
public void onStart()
{
    super.onStart();
    AndroidBug5497Workaround.getInstance(getActivity()).setListener();
}

@Override
public void onStop()
{
    super.onStop();
    AndroidBug5497Workaround.getInstance(getActivity()).removeListener();
}

How to name variables on the fly?

FAQ says:

If you have

varname <- c("a", "b", "d")

you can do

get(varname[1]) + 2

for

a + 2

or

assign(varname[1], 2 + 2)

for

a <- 2 + 2

So it looks like you use GET when you want to evaluate a formula that uses a variable (such as a concatenate), and ASSIGN when you want to assign a value to a pre-declared variable.

Syntax for assign: assign(x, value)

x: a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.

value: value to be assigned to x.

font awesome icon in select option

Full Sample and newer version:https://codepen.io/Nagibaba/pen/bagEgx enter image description here

_x000D_
_x000D_
select {_x000D_
  font-family: 'FontAwesome', 'sans-serif';_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<div>_x000D_
  <select>_x000D_
    <option value="fa-align-left">&#xf036; fa-align-left</option>_x000D_
    <option value="fa-align-right">&#xf038; fa-align-right</option>_x000D_
    <option value="fa-amazon">&#xf270; fa-amazon</option>_x000D_
    <option value="fa-ambulance">&#xf0f9; fa-ambulance</option>_x000D_
    <option value="fa-anchor">&#xf13d; fa-anchor</option>_x000D_
    <option value="fa-android">&#xf17b; fa-android</option>_x000D_
    <option value="fa-angellist">&#xf209; fa-angellist</option>_x000D_
    <option value="fa-angle-double-down">&#xf103; fa-angle-double-down</option>_x000D_
    <option value="fa-angle-double-left">&#xf100; fa-angle-double-left</option>_x000D_
    <option value="fa-angle-double-right">&#xf101; fa-angle-double-right</option>_x000D_
    <option value="fa-angle-double-up">&#xf102; fa-angle-double-up</option>_x000D_
_x000D_
    <option value="fa-angle-left">&#xf104; fa-angle-left</option>_x000D_
    <option value="fa-angle-right">&#xf105; fa-angle-right</option>_x000D_
    <option value="fa-angle-up">&#xf106; fa-angle-up</option>_x000D_
    <option value="fa-apple">&#xf179; fa-apple</option>_x000D_
    <option value="fa-archive">&#xf187; fa-archive</option>_x000D_
    <option value="fa-area-chart">&#xf1fe; fa-area-chart</option>_x000D_
    <option value="fa-arrow-circle-down">&#xf0ab; fa-arrow-circle-down</option>_x000D_
    <option value="fa-arrow-circle-left">&#xf0a8; fa-arrow-circle-left</option>_x000D_
    <option value="fa-arrow-circle-o-down">&#xf01a; fa-arrow-circle-o-down</option>_x000D_
    <option value="fa-arrow-circle-o-left">&#xf190; fa-arrow-circle-o-left</option>_x000D_
    <option value="fa-arrow-circle-o-right">&#xf18e; fa-arrow-circle-o-right</option>_x000D_
    <option value="fa-arrow-circle-o-up">&#xf01b; fa-arrow-circle-o-up</option>_x000D_
    <option value="fa-arrow-circle-right">&#xf0a9; fa-arrow-circle-right</option>_x000D_
    <option value="fa-arrow-circle-up">&#xf0aa; fa-arrow-circle-up</option>_x000D_
    <option value="fa-arrow-down">&#xf063; fa-arrow-down</option>_x000D_
    <option value="fa-arrow-left">&#xf060; fa-arrow-left</option>_x000D_
    <option value="fa-arrow-right">&#xf061; fa-arrow-right</option>_x000D_
    <option value="fa-arrow-up">&#xf062; fa-arrow-up</option>_x000D_
    <option value="fa-arrows">&#xf047; fa-arrows</option>_x000D_
    <option value="fa-arrows-alt">&#xf0b2; fa-arrows-alt</option>_x000D_
    <option value="fa-arrows-h">&#xf07e; fa-arrows-h</option>_x000D_
    <option value="fa-arrows-v">&#xf07d; fa-arrows-v</option>_x000D_
    <option value="fa-asterisk">&#xf069; fa-asterisk</option>_x000D_
    <option value="fa-at">&#xf1fa; fa-at</option>_x000D_
    <option value="fa-automobile">&#xf1b9; fa-automobile</option>_x000D_
    <option value="fa-backward">&#xf04a; fa-backward</option>_x000D_
    <option value="fa-balance-scale">&#xf24e; fa-balance-scale</option>_x000D_
    <option value="fa-ban">&#xf05e; fa-ban</option>_x000D_
    <option value="fa-bank">&#xf19c; fa-bank</option>_x000D_
    <option value="fa-bar-chart">&#xf080; fa-bar-chart</option>_x000D_
    <option value="fa-bar-chart-o">&#xf080; fa-bar-chart-o</option>_x000D_
_x000D_
    <option value="fa-battery-full">&#xf240; fa-battery-full</option>_x000D_
    n value="fa-beer">&#xf0fc; fa-beer</option>_x000D_
    <option value="fa-behance">&#xf1b4; fa-behance</option>_x000D_
    <option value="fa-behance-square">&#xf1b5; fa-behance-square</option>_x000D_
    <option value="fa-bell">&#xf0f3; fa-bell</option>_x000D_
    <option value="fa-bell-o">&#xf0a2; fa-bell-o</option>_x000D_
    <option value="fa-bell-slash">&#xf1f6; fa-bell-slash</option>_x000D_
    <option value="fa-bell-slash-o">&#xf1f7; fa-bell-slash-o</option>_x000D_
    <option value="fa-bicycle">&#xf206; fa-bicycle</option>_x000D_
    <option value="fa-binoculars">&#xf1e5; fa-binoculars</option>_x000D_
    <option value="fa-birthday-cake">&#xf1fd; fa-birthday-cake</option>_x000D_
    <option value="fa-bitbucket">&#xf171; fa-bitbucket</option>_x000D_
    <option value="fa-bitbucket-square">&#xf172; fa-bitbucket-square</option>_x000D_
    <option value="fa-bitcoin">&#xf15a; fa-bitcoin</option>_x000D_
    <option value="fa-black-tie">&#xf27e; fa-black-tie</option>_x000D_
    <option value="fa-bold">&#xf032; fa-bold</option>_x000D_
    <option value="fa-bolt">&#xf0e7; fa-bolt</option>_x000D_
    <option value="fa-bomb">&#xf1e2; fa-bomb</option>_x000D_
    <option value="fa-book">&#xf02d; fa-book</option>_x000D_
    <option value="fa-bookmark">&#xf02e; fa-bookmark</option>_x000D_
    <option value="fa-bookmark-o">&#xf097; fa-bookmark-o</option>_x000D_
    <option value="fa-briefcase">&#xf0b1; fa-briefcase</option>_x000D_
    <option value="fa-btc">&#xf15a; fa-btc</option>_x000D_
    <option value="fa-bug">&#xf188; fa-bug</option>_x000D_
    <option value="fa-building">&#xf1ad; fa-building</option>_x000D_
    <option value="fa-building-o">&#xf0f7; fa-building-o</option>_x000D_
    <option value="fa-bullhorn">&#xf0a1; fa-bullhorn</option>_x000D_
    <option value="fa-bullseye">&#xf140; fa-bullseye</option>_x000D_
    <option value="fa-bus">&#xf207; fa-bus</option>_x000D_
    <option value="fa-cab">&#xf1ba; fa-cab</option>_x000D_
    <option value="fa-calendar">&#xf073; fa-calendar</option>_x000D_
    <option value="fa-camera">&#xf030; fa-camera</option>_x000D_
    <option value="fa-car">&#xf1b9; fa-car</option>_x000D_
    <option value="fa-caret-up">&#xf0d8; fa-caret-up</option>_x000D_
    <option value="fa-cart-plus">&#xf217; fa-cart-plus</option>_x000D_
    <option value="fa-cc">&#xf20a; fa-cc</option>_x000D_
    <option value="fa-cc-amex">&#xf1f3; fa-cc-amex</option>_x000D_
    <option value="fa-cc-jcb">&#xf24b; fa-cc-jcb</option>_x000D_
    <option value="fa-cc-paypal">&#xf1f4; fa-cc-paypal</option>_x000D_
    <option value="fa-cc-stripe">&#xf1f5; fa-cc-stripe</option>_x000D_
    <option value="fa-cc-visa">&#xf1f0; fa-cc-visa</option>_x000D_
    <option value="fa-chain">&#xf0c1; fa-chain</option>_x000D_
    <option value="fa-check">&#xf00c; fa-check</option>_x000D_
    <option value="fa-chevron-left">&#xf053; fa-chevron-left</option>_x000D_
    <option value="fa-chevron-right">&#xf054; fa-chevron-right</option>_x000D_
    <option value="fa-chevron-up">&#xf077; fa-chevron-up</option>_x000D_
    <option value="fa-child">&#xf1ae; fa-child</option>_x000D_
    <option value="fa-chrome">&#xf268; fa-chrome</option>_x000D_
    <option value="fa-circle">&#xf111; fa-circle</option>_x000D_
    <option value="fa-circle-o">&#xf10c; fa-circle-o</option>_x000D_
    <option value="fa-circle-o-notch">&#xf1ce; fa-circle-o-notch</option>_x000D_
    <option value="fa-circle-thin">&#xf1db; fa-circle-thin</option>_x000D_
    <option value="fa-clipboard">&#xf0ea; fa-clipboard</option>_x000D_
    <option value="fa-clock-o">&#xf017; fa-clock-o</option>_x000D_
    <option value="fa-clone">&#xf24d; fa-clone</option>_x000D_
    <option value="fa-close">&#xf00d; fa-close</option>_x000D_
    <option value="fa-cloud">&#xf0c2; fa-cloud</option>_x000D_
    <option value="fa-cloud-download">&#xf0ed; fa-cloud-download</option>_x000D_
    <option value="fa-cloud-upload">&#xf0ee; fa-cloud-upload</option>_x000D_
    <option value="fa-cny">&#xf157; fa-cny</option>_x000D_
    <option value="fa-code">&#xf121; fa-code</option>_x000D_
    <option value="fa-code-fork">&#xf126; fa-code-fork</option>_x000D_
    <option value="fa-codepen">&#xf1cb; fa-codepen</option>_x000D_
    <option value="fa-coffee">&#xf0f4; fa-coffee</option>_x000D_
    <option value="fa-cog">&#xf013; fa-cog</option>_x000D_
    <option value="fa-cogs">&#xf085; fa-cogs</option>_x000D_
    <option value="fa-columns">&#xf0db; fa-columns</option>_x000D_
    <option value="fa-comment">&#xf075; fa-comment</option>_x000D_
    <option value="fa-comment-o">&#xf0e5; fa-comment-o</option>_x000D_
    <option value="fa-commenting">&#xf27a; fa-commenting</option>_x000D_
    <option value="fa-commenting-o">&#xf27b; fa-commenting-o</option>_x000D_
    <option value="fa-comments">&#xf086; fa-comments</option>_x000D_
    <option value="fa-comments-o">&#xf0e6; fa-comments-o</option>_x000D_
    <option value="fa-compass">&#xf14e; fa-compass</option>_x000D_
    <option value="fa-compress">&#xf066; fa-compress</option>_x000D_
    <option value="fa-connectdevelop">&#xf20e; fa-connectdevelop</option>_x000D_
    <option value="fa-contao">&#xf26d; fa-contao</option>_x000D_
    <option value="fa-copy">&#xf0c5; fa-copy</option>_x000D_
    <option value="fa-copyright">&#xf1f9; fa-copyright</option>_x000D_
    <option value="fa-creative-commons">&#xf25e; fa-creative-commons</option>_x000D_
    <option value="fa-credit-card">&#xf09d; fa-credit-card</option>_x000D_
    <option value="fa-crop">&#xf125; fa-crop</option>_x000D_
    <option value="fa-crosshairs">&#xf05b; fa-crosshairs</option>_x000D_
    <option value="fa-css3">&#xf13c; fa-css3</option>_x000D_
    <option value="fa-cube">&#xf1b2; fa-cube</option>_x000D_
    <option value="fa-cubes">&#xf1b3; fa-cubes</option>_x000D_
    <option value="fa-cut">&#xf0c4; fa-cut</option>_x000D_
    <option value="fa-cutlery">&#xf0f5; fa-cutlery</option>_x000D_
    <option value="fa-dashboard">&#xf0e4; fa-dashboard</option>_x000D_
    <option value="fa-dashcube">&#xf210; fa-dashcube</option>_x000D_
    <option value="fa-database">&#xf1c0; fa-database</option>_x000D_
    <option value="fa-dedent">&#xf03b; fa-dedent</option>_x000D_
    <option value="fa-delicious">&#xf1a5; fa-delicious</option>_x000D_
    <option value="fa-desktop">&#xf108; fa-desktop</option>_x000D_
    <option value="fa-deviantart">&#xf1bd; fa-deviantart</option>_x000D_
    <option value="fa-diamond">&#xf219; fa-diamond</option>_x000D_
    <option value="fa-digg">&#xf1a6; fa-digg</option>_x000D_
    <option value="fa-dollar">&#xf155; fa-dollar</option>_x000D_
    <option value="fa-download">&#xf019; fa-download</option>_x000D_
    <option value="fa-dribbble">&#xf17d; fa-dribbble</option>_x000D_
    <option value="fa-dropbox">&#xf16b; fa-dropbox</option>_x000D_
    <option value="fa-drupal">&#xf1a9; fa-drupal</option>_x000D_
    <option value="fa-edit">&#xf044; fa-edit</option>_x000D_
    <option value="fa-eject">&#xf052; fa-eject</option>_x000D_
    <option value="fa-ellipsis-h">&#xf141; fa-ellipsis-h</option>_x000D_
    <option value="fa-ellipsis-v">&#xf142; fa-ellipsis-v</option>_x000D_
    <option value="fa-empire">&#xf1d1; fa-empire</option>_x000D_
    <option value="fa-envelope">&#xf0e0; fa-envelope</option>_x000D_
    <option value="fa-envelope-o">&#xf003; fa-envelope-o</option>_x000D_
    <option value="fa-eur">&#xf153; fa-eur</option>_x000D_
    <option value="fa-euro">&#xf153; fa-euro</option>_x000D_
    <option value="fa-exchange">&#xf0ec; fa-exchange</option>_x000D_
    <option value="fa-exclamation">&#xf12a; fa-exclamation</option>_x000D_
    <option value="fa-exclamation-circle">&#xf06a; fa-exclamation-circle</option>_x000D_
    <option value="fa-exclamation-triangle">&#xf071; fa-exclamation-triangle</option>_x000D_
    <option value="fa-expand">&#xf065; fa-expand</option>_x000D_
    <option value="fa-expeditedssl">&#xf23e; fa-expeditedssl</option>_x000D_
    <option value="fa-external-link">&#xf08e; fa-external-link</option>_x000D_
    <option value="fa-external-link-square">&#xf14c; fa-external-link-square</option>_x000D_
    <option value="fa-eye">&#xf06e; fa-eye</option>_x000D_
    <option value="fa-eye-slash">&#xf070; fa-eye-slash</option>_x000D_
    <option value="fa-eyedropper">&#xf1fb; fa-eyedropper</option>_x000D_
    <option value="fa-facebook">&#xf09a; fa-facebook</option>_x000D_
    <option value="fa-facebook-f">&#xf09a; fa-facebook-f</option>_x000D_
    <option value="fa-facebook-official">&#xf230; fa-facebook-official</option>_x000D_
    <option value="fa-facebook-square">&#xf082; fa-facebook-square</option>_x000D_
    <option value="fa-fast-backward">&#xf049; fa-fast-backward</option>_x000D_
    <option value="fa-fast-forward">&#xf050; fa-fast-forward</option>_x000D_
    <option value="fa-fax">&#xf1ac; fa-fax</option>_x000D_
    <option value="fa-feed">&#xf09e; fa-feed</option>_x000D_
    <option value="fa-female">&#xf182; fa-female</option>_x000D_
    <option value="fa-fighter-jet">&#xf0fb; fa-fighter-jet</option>_x000D_
    <option value="fa-file">&#xf15b; fa-file</option>_x000D_
    <option value="fa-file-archive-o">&#xf1c6; fa-file-archive-o</option>_x000D_
    <option value="fa-file-audio-o">&#xf1c7; fa-file-audio-o</option>_x000D_
    <option value="fa-file-code-o">&#xf1c9; fa-file-code-o</option>_x000D_
    <option value="fa-file-excel-o">&#xf1c3; fa-file-excel-o</option>_x000D_
    <option value="fa-file-image-o">&#xf1c5; fa-file-image-o</option>_x000D_
    <option value="fa-file-movie-o">&#xf1c8; fa-file-movie-o</option>_x000D_
    <option value="fa-file-o">&#xf016; fa-file-o</option>_x000D_
    <option value="fa-file-pdf-o">&#xf1c1; fa-file-pdf-o</option>_x000D_
    <option value="fa-file-photo-o">&#xf1c5; fa-file-photo-o</option>_x000D_
    <option value="fa-file-picture-o">&#xf1c5; fa-file-picture-o</option>_x000D_
    <option value="fa-file-powerpoint-o">&#xf1c4; fa-file-powerpoint-o</option>_x000D_
    <option value="fa-file-sound-o">&#xf1c7; fa-file-sound-o</option>_x000D_
    <option value="fa-file-text">&#xf15c; fa-file-text</option>_x000D_
    <option value="fa-file-text-o">&#xf0f6; fa-file-text-o</option>_x000D_
    <option value="fa-file-video-o">&#xf1c8; fa-file-video-o</option>_x000D_
    <option value="fa-file-word-o">&#xf1c2; fa-file-word-o</option>_x000D_
    <option value="fa-file-zip-o">&#xf1c6; fa-file-zip-o</option>_x000D_
    <option value="fa-files-o">&#xf0c5; fa-files-o</option>_x000D_
    <option value="fa-film">&#xf008; fa-film</option>_x000D_
    <option value="fa-filter">&#xf0b0; fa-filter</option>_x000D_
    <option value="fa-fire">&#xf06d; fa-fire</option>_x000D_
    <option value="fa-fire-extinguisher">&#xf134; fa-fire-extinguisher</option>_x000D_
    <option value="fa-firefox">&#xf269; fa-firefox</option>_x000D_
    <option value="fa-flag">&#xf024; fa-flag</option>_x000D_
    <option value="fa-flag-checkered">&#xf11e; fa-flag-checkered</option>_x000D_
    <option value="fa-flag-o">&#xf11d; fa-flag-o</option>_x000D_
    <option value="fa-flash">&#xf0e7; fa-flash</option>_x000D_
    <option value="fa-flask">&#xf0c3; fa-flask</option>_x000D_
    <option value="fa-flickr">&#xf16e; fa-flickr</option>_x000D_
    <option value="fa-floppy-o">&#xf0c7; fa-floppy-o</option>_x000D_
    <option value="fa-folder">&#xf07b; fa-folder</option>_x000D_
    <option value="fa-folder-o">&#xf114; fa-folder-o</option>_x000D_
    <option value="fa-folder-open">&#xf07c; fa-folder-open</option>_x000D_
    <option value="fa-folder-open-o">&#xf115; fa-folder-open-o</option>_x000D_
    <option value="fa-font">&#xf031; fa-font</option>_x000D_
    <option value="fa-fonticons">&#xf280; fa-fonticons</option>_x000D_
    <option value="fa-forumbee">&#xf211; fa-forumbee</option>_x000D_
    <option value="fa-forward">&#xf04e; fa-forward</option>_x000D_
    <option value="fa-foursquare">&#xf180; fa-foursquare</option>_x000D_
    <option value="fa-frown-o">&#xf119; fa-frown-o</option>_x000D_
    <option value="fa-futbol-o">&#xf1e3; fa-futbol-o</option>_x000D_
    <option value="fa-gamepad">&#xf11b; fa-gamepad</option>_x000D_
    <option value="fa-gavel">&#xf0e3; fa-gavel</option>_x000D_
    <option value="fa-gbp">&#xf154; fa-gbp</option>_x000D_
    <option value="fa-ge">&#xf1d1; fa-ge</option>_x000D_
    <option value="fa-gear">&#xf013; fa-gear</option>_x000D_
    <option value="fa-gears">&#xf085; fa-gears</option>_x000D_
    <option value="fa-genderless">&#xf22d; fa-genderless</option>_x000D_
    <option value="fa-get-pocket">&#xf265; fa-get-pocket</option>_x000D_
    <option value="fa-gg">&#xf260; fa-gg</option>_x000D_
    <option value="fa-gg-circle">&#xf261; fa-gg-circle</option>_x000D_
    <option value="fa-gift">&#xf06b; fa-gift</option>_x000D_
    <option value="fa-git">&#xf1d3; fa-git</option>_x000D_
    <option value="fa-git-square">&#xf1d2; fa-git-square</option>_x000D_
    <option value="fa-github">&#xf09b; fa-github</option>_x000D_
    <option value="fa-github-alt">&#xf113; fa-github-alt</option>_x000D_
    <option value="fa-github-square">&#xf092; fa-github-square</option>_x000D_
    <option value="fa-gittip">&#xf184; fa-gittip</option>_x000D_
    <option value="fa-glass">&#xf000; fa-glass</option>_x000D_
    <option value="fa-globe">&#xf0ac; fa-globe</option>_x000D_
    <option value="fa-google">&#xf1a0; fa-google</option>_x000D_
    <option value="fa-google-plus">&#xf0d5; fa-google-plus</option>_x000D_
    <option value="fa-google-plus-square">&#xf0d4; fa-google-plus-square</option>_x000D_
    <option value="fa-google-wallet">&#xf1ee; fa-google-wallet</option>_x000D_
    <option value="fa-graduation-cap">&#xf19d; fa-graduation-cap</option>_x000D_
    <option value="fa-gratipay">&#xf184; fa-gratipay</option>_x000D_
    <option value="fa-group">&#xf0c0; fa-group</option>_x000D_
    <option value="fa-h-square">&#xf0fd; fa-h-square</option>_x000D_
    <option value="fa-hacker-news">&#xf1d4; fa-hacker-news</option>_x000D_
    <option value="fa-hand-grab-o">&#xf255; fa-hand-grab-o</option>_x000D_
    <option value="fa-hand-lizard-o">&#xf258; fa-hand-lizard-o</option>_x000D_
    <option value="fa-hand-o-down">&#xf0a7; fa-hand-o-down</option>_x000D_
    <option value="fa-hand-o-left">&#xf0a5; fa-hand-o-left</option>_x000D_
    <option value="fa-hand-o-right">&#xf0a4; fa-hand-o-right</option>_x000D_
    <option value="fa-hand-o-up">&#xf0a6; fa-hand-o-up</option>_x000D_
    <option value="fa-hand-paper-o">&#xf256; fa-hand-paper-o</option>_x000D_
    <option value="fa-hand-peace-o">&#xf25b; fa-hand-peace-o</option>_x000D_
    <option value="fa-hand-pointer-o">&#xf25a; fa-hand-pointer-o</option>_x000D_
    <option value="fa-hand-rock-o">&#xf255; fa-hand-rock-o</option>_x000D_
    <option value="fa-hand-scissors-o">&#xf257; fa-hand-scissors-o</option>_x000D_
    <option value="fa-hand-spock-o">&#xf259; fa-hand-spock-o</option>_x000D_
    <option value="fa-hand-stop-o">&#xf256; fa-hand-stop-o</option>_x000D_
    <option value="fa-hdd-o">&#xf0a0; fa-hdd-o</option>_x000D_
    <option value="fa-header">&#xf1dc; fa-header</option>_x000D_
    <option value="fa-headphones">&#xf025; fa-headphones</option>_x000D_
    <option value="fa-heart">&#xf004; fa-heart</option>_x000D_
    <option value="fa-heart-o">&#xf08a; fa-heart-o</option>_x000D_
    <option value="fa-heartbeat">&#xf21e; fa-heartbeat</option>_x000D_
    <option value="fa-history">&#xf1da; fa-history</option>_x000D_
    <option value="fa-home">&#xf015; fa-home</option>_x000D_
    <option value="fa-hospital-o">&#xf0f8; fa-hospital-o</option>_x000D_
    <option value="fa-hotel">&#xf236; fa-hotel</option>_x000D_
    <option value="fa-hourglass">&#xf254; fa-hourglass</option>_x000D_
    <option value="fa-hourglass-1">&#xf251; fa-hourglass-1</option>_x000D_
    <option value="fa-hourglass-2">&#xf252; fa-hourglass-2</option>_x000D_
    <option value="fa-hourglass-3">&#xf253; fa-hourglass-3</option>_x000D_
    <option value="fa-hourglass-end">&#xf253; fa-hourglass-end</option>_x000D_
    <option value="fa-hourglass-half">&#xf252; fa-hourglass-half</option>_x000D_
    <option value="fa-hourglass-o">&#xf250; fa-hourglass-o</option>_x000D_
    <option value="fa-hourglass-start">&#xf251; fa-hourglass-start</option>_x000D_
    <option value="fa-houzz">&#xf27c; fa-houzz</option>_x000D_
    <option value="fa-html5">&#xf13b; fa-html5</option>_x000D_
    <option value="fa-i-cursor">&#xf246; fa-i-cursor</option>_x000D_
    <option value="fa-ils">&#xf20b; fa-ils</option>_x000D_
    <option value="fa-image">&#xf03e; fa-image</option>_x000D_
    <option value="fa-inbox">&#xf01c; fa-inbox</option>_x000D_
    <option value="fa-indent">&#xf03c; fa-indent</option>_x000D_
    <option value="fa-industry">&#xf275; fa-industry</option>_x000D_
    <option value="fa-info">&#xf129; fa-info</option>_x000D_
    <option value="fa-info-circle">&#xf05a; fa-info-circle</option>_x000D_
    <option value="fa-inr">&#xf156; fa-inr</option>_x000D_
    <option value="fa-instagram">&#xf16d; fa-instagram</option>_x000D_
    <option value="fa-institution">&#xf19c; fa-institution</option>_x000D_
    <option value="fa-internet-explorer">&#xf26b; fa-internet-explorer</option>_x000D_
    <option value="fa-intersex">&#xf224; fa-intersex</option>_x000D_
    <option value="fa-ioxhost">&#xf208; fa-ioxhost</option>_x000D_
    <option value="fa-italic">&#xf033; fa-italic</option>_x000D_
    <option value="fa-joomla">&#xf1aa; fa-joomla</option>_x000D_
    <option value="fa-jpy">&#xf157; fa-jpy</option>_x000D_
    <option value="fa-jsfiddle">&#xf1cc; fa-jsfiddle</option>_x000D_
    <option value="fa-key">&#xf084; fa-key</option>_x000D_
    <option value="fa-keyboard-o">&#xf11c; fa-keyboard-o</option>_x000D_
    <option value="fa-krw">&#xf159; fa-krw</option>_x000D_
    <option value="fa-language">&#xf1ab; fa-language</option>_x000D_
    <option value="fa-laptop">&#xf109; fa-laptop</option>_x000D_
    <option value="fa-lastfm">&#xf202; fa-lastfm</option>_x000D_
    <option value="fa-lastfm-square">&#xf203; fa-lastfm-square</option>_x000D_
    <option value="fa-leaf">&#xf06c; fa-leaf</option>_x000D_
    <option value="fa-leanpub">&#xf212; fa-leanpub</option>_x000D_
    <option value="fa-legal">&#xf0e3; fa-legal</option>_x000D_
    <option value="fa-lemon-o">&#xf094; fa-lemon-o</option>_x000D_
    <option value="fa-level-down">&#xf149; fa-level-down</option>_x000D_
    <option value="fa-level-up">&#xf148; fa-level-up</option>_x000D_
    <option value="fa-life-bouy">&#xf1cd; fa-life-bouy</option>_x000D_
    <option value="fa-life-buoy">&#xf1cd; fa-life-buoy</option>_x000D_
    <option value="fa-life-ring">&#xf1cd; fa-life-ring</option>_x000D_
    <option value="fa-life-saver">&#xf1cd; fa-life-saver</option>_x000D_
    <option value="fa-lightbulb-o">&#xf0eb; fa-lightbulb-o</option>_x000D_
    <option value="fa-line-chart">&#xf201; fa-line-chart</option>_x000D_
    <option value="fa-link">&#xf0c1; fa-link</option>_x000D_
    <option value="fa-linkedin">&#xf0e1; fa-linkedin</option>_x000D_
    <option value="fa-linkedin-square">&#xf08c; fa-linkedin-square</option>_x000D_
    <option value="fa-linux">&#xf17c; fa-linux</option>_x000D_
    <option value="fa-list">&#xf03a; fa-list</option>_x000D_
    <option value="fa-list-alt">&#xf022; fa-list-alt</option>_x000D_
    <option value="fa-list-ol">&#xf0cb; fa-list-ol</option>_x000D_
    <option value="fa-list-ul">&#xf0ca; fa-list-ul</option>_x000D_
    <option value="fa-location-arrow">&#xf124; fa-location-arrow</option>_x000D_
    <option value="fa-lock">&#xf023; fa-lock</option>_x000D_
    <option value="fa-long-arrow-down">&#xf175; fa-long-arrow-down</option>_x000D_
    <option value="fa-long-arrow-left">&#xf177; fa-long-arrow-left</option>_x000D_
    <option value="fa-long-arrow-right">&#xf178; fa-long-arrow-right</option>_x000D_
    <option value="fa-long-arrow-up">&#xf176; fa-long-arrow-up</option>_x000D_
    <option value="fa-magic">&#xf0d0; fa-magic</option>_x000D_
    <option value="fa-magnet">&#xf076; fa-magnet</option>_x000D_
_x000D_
    <option value="fa-mars-stroke-v">&#xf22a; fa-mars-stroke-v</option>_x000D_
    <option value="fa-maxcdn">&#xf136; fa-maxcdn</option>_x000D_
    <option value="fa-meanpath">&#xf20c; fa-meanpath</option>_x000D_
    <option value="fa-medium">&#xf23a; fa-medium</option>_x000D_
    <option value="fa-medkit">&#xf0fa; fa-medkit</option>_x000D_
    <option value="fa-meh-o">&#xf11a; fa-meh-o</option>_x000D_
    <option value="fa-mercury">&#xf223; fa-mercury</option>_x000D_
    <option value="fa-microphone">&#xf130; fa-microphone</option>_x000D_
    <option value="fa-mobile">&#xf10b; fa-mobile</option>_x000D_
    <option value="fa-motorcycle">&#xf21c; fa-motorcycle</option>_x000D_
    <option value="fa-mouse-pointer">&#xf245; fa-mouse-pointer</option>_x000D_
    <option value="fa-music">&#xf001; fa-music</option>_x000D_
    <option value="fa-navicon">&#xf0c9; fa-navicon</option>_x000D_
    <option value="fa-neuter">&#xf22c; fa-neuter</option>_x000D_
    <option value="fa-newspaper-o">&#xf1ea; fa-newspaper-o</option>_x000D_
    <option value="fa-opencart">&#xf23d; fa-opencart</option>_x000D_
    <option value="fa-openid">&#xf19b; fa-openid</option>_x000D_
    <option value="fa-opera">&#xf26a; fa-opera</option>_x000D_
    <option value="fa-outdent">&#xf03b; fa-outdent</option>_x000D_
    <option value="fa-pagelines">&#xf18c; fa-pagelines</option>_x000D_
    <option value="fa-paper-plane-o">&#xf1d9; fa-paper-plane-o</option>_x000D_
    <option value="fa-paperclip">&#xf0c6; fa-paperclip</option>_x000D_
    <option value="fa-paragraph">&#xf1dd; fa-paragraph</option>_x000D_
    <option value="fa-paste">&#xf0ea; fa-paste</option>_x000D_
    <option value="fa-pause">&#xf04c; fa-pause</option>_x000D_
    <option value="fa-paw">&#xf1b0; fa-paw</option>_x000D_
    <option value="fa-paypal">&#xf1ed; fa-paypal</option>_x000D_
    <option value="fa-pencil">&#xf040; fa-pencil</option>_x000D_
    <option value="fa-pencil-square-o">&#xf044; fa-pencil-square-o</option>_x000D_
    <option value="fa-phone">&#xf095; fa-phone</option>_x000D_
    <option value="fa-photo">&#xf03e; fa-photo</option>_x000D_
    <option value="fa-picture-o">&#xf03e; fa-picture-o</option>_x000D_
    <option value="fa-pie-chart">&#xf200; fa-pie-chart</option>_x000D_
    <option value="fa-pied-piper">&#xf1a7; fa-pied-piper</option>_x000D_
    <option value="fa-pied-piper-alt">&#xf1a8; fa-pied-piper-alt</option>_x000D_
    <option value="fa-pinterest">&#xf0d2; fa-pinterest</option>_x000D_
    <option value="fa-pinterest-p">&#xf231; fa-pinterest-p</option>_x000D_
    <option value="fa-pinterest-square">&#xf0d3; fa-pinterest-square</option>_x000D_
    <option value="fa-plane">&#xf072; fa-plane</option>_x000D_
    <option value="fa-play">&#xf04b; fa-play</option>_x000D_
    <option value="fa-play-c
                  

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

How to find the serial port number on Mac OS X?

Try this: ioreg -p IOUSB -l -b | grep -E "@|PortNum|USB Serial Number"

Java, How to specify absolute value and square roots

Try using Math.abs:

variableAbs = Math.abs(variable);

For square root use:

variableSqRt = Math.sqrt(variable);

How can I change a file's encoding with vim?

Notice that there is a difference between

set encoding

and

set fileencoding

In the first case, you'll change the output encoding that is shown in the terminal. In the second case, you'll change the output encoding of the file that is written.

SQL Server Error : String or binary data would be truncated

this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case: you specify transaction_status varchar(10) but you actually trying to store
_transaction_status which contain 19 characters. that's why you faced this type of error in this code..

Push Notifications in Android Platform

There's a lot a third party servers like Urban Airship, Xtify, Mainline, ... whiches allow send not only on Android, but also on iOs, Windows Phone ...

Any way to make plot points in scatterplot more transparent in R?

If you decide to use ggplot2, you can set transparency of overlapping points using the alpha argument.

e.g.

library(ggplot2)
ggplot(diamonds, aes(carat, price)) + geom_point(alpha = 1/40)

Create sequence of repeated values, in sequence?

Another base R option could be gl():

gl(5, 3)

Where the output is a factor:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5

If integers are needed, you can convert it:

as.numeric(gl(5, 3))

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

How to store image in SQL Server database tables column

Insert Into FEMALE(ID, Image)
Select '1', BulkColumn 
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image

You will also need admin rights to run the query.

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

Refer this link for linux command linux http://linuxcommand.org/man_pages/grep1.html

for displaying line no ,line of code and file use this command in your terminal or cmd, GitBash(Powered by terminal)

grep -irn "YourStringToBeSearch"

Calling JavaScript Function From CodeBehind

Thank "Liko", just add a comment to his answer.

string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);

Added single quotes (') to variable, otherwise it will give error message:

string jsFunc = "myFunc('" + MyBackValue + "')";

Conditional HTML Attributes using Razor MVC3

You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...

<input type="text" id="@strElementID" class="@strCSSClass" />

If strCSSClass is null then the class attribute won't render at all.

SSSHHH...don't tell. :)

How do you use global variables or constant values in Ruby?

One thing you need to realize is in Ruby everything is an object. Given that, if you don't define your methods within Module or Class, Ruby will put it within the Object class. So, your code will be local to the Object scope.

A typical approach on Object Oriented Programming is encapsulate all logic within a class:

class Point
  attr_accessor :x, :y

  # If we don't specify coordinates, we start at 0.
  def initialize(x = 0, y = 0)
    # Notice that `@` indicates instance variables.
    @x = x
    @y = y
  end

  # Here we override the `+' operator.
  def +(point)
    Point.new(self.x + point.x, self.y + point.y)
  end

  # Here we draw the point.
  def draw(offset = nil)
    if offset.nil?
      new_point = self
    else
      new_point = self + offset 
    end
    new_point.draw_absolute
  end

  def draw_absolute
    puts "x: #{self.x}, y: #{self.y}"
  end
end

first_point = Point.new(100, 200)
second_point = Point.new(3, 4)

second_point.draw(first_point)

Hope this clarifies a bit.

determine DB2 text string length

Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;

how to reset <input type = "file">

Resetting a file upload button is so easy using pure JavaScript!

There are few ways to do it, but the must straightforward way which is working well in many browser is changing the filed value to nothing, that way the upload filed gets reset, also try to use pure javascript rather than any framework, I created the code below, just check it out (ES6):

_x000D_
_x000D_
function resetFile() {_x000D_
  const file = document.querySelector('.file');_x000D_
  file.value = '';_x000D_
}
_x000D_
<input type="file" class="file" />_x000D_
<button onclick="resetFile()">Reset file</button>
_x000D_
_x000D_
_x000D_

jQuery scroll to ID from different page

I've written something that detects if the page contains the anchor that was clicked on, and if not, goes to the normal page, otherwise it scrolls to the specific section:

$('a[href*=\\#]').on('click',function(e) {

    var target = this.hash;
    var $target = $(target);
    console.log(targetname);
    var targetname = target.slice(1, target.length);

    if(document.getElementById(targetname) != null) {
         e.preventDefault();
    }
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top-120 //or the height of your fixed navigation 

    }, 900, 'swing', function () {
        window.location.hash = target;
  });
});

eclipse won't start - no java virtual machine was found

In my case the problem was that the path was enclosed in quotation marks ("):

-vm 
"C:\Program Files\Java\jdk1.8.0_25\bin"

Removing them fixed the problem:

-vm 
C:\Program Files\Java\jdk1.8.0_25\bin

how to remove "," from a string in javascript

You aren't assigning the result of the replace method back to your variable. When you call replace, it returns a new string without modifying the old one.

For example, load this into your favorite browser:

<html><head></head><body>
    <script type="text/javascript">
        var str1 = "a,d,k";
        str1.replace(/\,/g,"");
        var str2 = str1.replace(/\,/g,"");
        alert (str1);
        alert (str2);
    </script>
</body></html>

In this case, str1 will still be "a,d,k" and str2 will be "adk".

If you want to change str1, you should be doing:

var str1 = "a,d,k";
str1 = str1.replace (/,/g, "");

Equal sized table cells to fill the entire width of the containing table

You don't even have to set a specific width for the cells, table-layout: fixed suffices to spread the cells evenly.

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid hotpink;_x000D_
    vertical-align: middle;_x000D_
    word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that for table-layout to work the table styled element must have a width set (100% in my example).

Pods stuck in Terminating status

I'd not recommend force deleting pods unless container already exited.

  1. Verify kubelet logs to see what is causing the issue "journalctl -u kubelet"
  2. Verify docker logs: journalctl -u docker.service
  3. Check if pod's volume mount points still exist and if anyone holds lock on it.
  4. Verify if host is out of memory or disk

PL/SQL block problem: No data found error

Your SELECT statement isn't finding the data you're looking for. That is, there is no record in the ENROLLMENT table with the given STUDENT_ID and SECTION_ID. You may want to try putting some DBMS_OUTPUT.PUT_LINE statements before you run the query, printing the values of v_student_id and v_section_id. They may not be containing what you expect them to contain.

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

HTML:

<div class="container">
    <div class="box">
        <img src="http://lorempixel.com/1600/1200/" alt="">
    </div>
</div>

CSS:

.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: stretch;

  width: 100%;
  height: 100%;

  border-radius: 4px;
  background-color: hsl(0, 0%, 96%);
}

.box {
  border-radius: 4px;
  display: flex;
}

.box img {
  width: 100%;
  object-fit: contain;
  border-radius: 4px;
}

Can I set enum start value in Java?

I think you're confused from looking at C++ enumerators. Java enumerators are different.

This would be the code if you are used to C/C++ enums:

public class TestEnum {
enum ids {
    OPEN,
    CLOSE,
    OTHER;

    public final int value = 100 + ordinal();
};

public static void main(String arg[]) {
    System.out.println("OPEN:  " + ids.OPEN.value);
    System.out.println("CLOSE: " + ids.CLOSE.value);
    System.out.println("OTHER: " + ids.OTHER.value);
}
};

Focusable EditText inside ListView

My task was to implement ListView which expands when clicked. The additional space shows EditText where you can input some text. App should be functional on 2.2+ (up to 4.2.2 at time of writing this)

I tried numerous solutions from this post and others I could find; tested them on 2.2 up to 4.2.2 devices. None of solutions was satisfactionary on all devices 2.2+, each solution presented with different problems.

I wanted to share my final solution :

  1. set listview to android:descendantFocusability="afterDescendants"
  2. set listview to setItemsCanFocus(true);
  3. set your activity to android:windowSoftInputMode="adjustResize" Many people suggest adjustPan but adjustResize gives much better ux imho, just test this in your case. With adjustPan you will get bottom listitems obscured for instance. Docs suggest that ("This is generally less desirable than resizing"). Also on 4.0.4 after user starts typing on soft keyboard the screen pans to the top.
  4. on 4.2.2 with adjustResize there are some problems with EditText focus. The solution is to apply rjrjr solution from this thread. It looks scarry but it is not. And it works. Just try it.

Additional 5. Due to adapter being refreshed (because of view resize) when EditText gains focus on pre HoneyComb versions I found an issue with reversed views: getting View for ListView item / reverse order on 2.2; works on 4.0.3

If you are doing some animations you might want to change behaviour to adjustPan for pre-honeycomb versions so that resize doesnt fire and adapter doesn't refresh the views. You just need to add something like this

if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

All this gives acceptable ux on 2.2 - 4.2.2 devices. Hope it will save people some time as it took me at least several hours to come to this conclusion.

How do I delete an item or object from an array using ng-click?

To remove item you need to remove it from array and can pass bday item to your remove function in markup. Then in controller look up the index of item and remove from array

<a class="btn" ng-click="remove(item)">Delete</a>

Then in controller:

$scope.remove = function(item) { 
  var index = $scope.bdays.indexOf(item);
  $scope.bdays.splice(index, 1);     
}

Angular will automatically detect the change to the bdays array and do the update of ng-repeat

DEMO: http://plnkr.co/edit/ZdShIA?p=preview

EDIT: If doing live updates with server would use a service you create using $resource to manage the array updates at same time it updates server

How to change color in markdown cells ipython/jupyter notebook?

<p style="font-family: Arial; font-size:1.4em;color:gold;"> Golden </p>

or

Text <span style="font-family: Arial; font-size:1.4em;color:gold;"> Golden </p> Text

Reading a text file with SQL Server

if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.

Ajax Success and Error function failure

I was having the same issue and fixed it by simply adding a dataType = "text" line to my ajax call. Make the dataType match the response you expect to get back from the server (your "insert successful" or "something went wrong" error message).

Pandas Replace NaN with blank/empty string

Try this,

add inplace=True

import numpy as np
df.replace(np.NaN, ' ', inplace=True)

ngFor with index as value in attribute

In Angular 5/6/7/8:

<ul>
  <li *ngFor="let item of items; index as i">
    {{i+1}} {{item}}
  </li>
</ul>

In older versions

<ul *ngFor="let item of items; index as i">
  <li>{{i+1}} {{item}}</li>
</ul>

Angular.io ? API ? NgForOf

Unit test examples

Another interesting example

Parsing JSON Array within JSON Object

mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.

The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)

Try this:

JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 

How to run DOS/CMD/Command Prompt commands from VB.NET?

You Can try This To Run Command Then cmd Exits

Process.Start("cmd", "/c YourCode")

You Can try This To Run The Command And Let cmd Wait For More Commands

Process.Start("cmd", "/k YourCode")

Android emulator doesn't take keyboard input - SDK tools rev 20

Restarting the emulator helps sometimes when typing is unavailable - despite keyboard input being enabled for your Android Virtual Device.

What do \t and \b do?

Backspace and tab both move the cursor position. Neither is truly a 'printable' character.

Your code says:

  1. print "foo"
  2. move the cursor back one space
  3. move the cursor forward to the next tabstop
  4. output "bar".

To get the output you expect, you need printf("foo\b \tbar"). Note the extra 'space'. That says:

  1. output "foo"
  2. move the cursor back one space
  3. output a ' ' (this replaces the second 'o').
  4. move the cursor forward to the next tabstop
  5. output "bar".

Most of the time it is inappropriate to use tabs and backspace for formatting your program output. Learn to use printf() formatting specifiers. Rendering of tabs can vary drastically depending on how the output is viewed.

This little script shows one way to alter your terminal's tab rendering. Tested on Ubuntu + gnome-terminal:

#!/bin/bash
tabs -8 
echo -e "\tnormal tabstop"
for x in `seq 2 10`; do
  tabs $x
  echo -e "\ttabstop=$x"
 done

tabs -8
echo -e "\tnormal tabstop"

Also see man setterm and regtabs.

And if you redirect your output or just write to a file, tabs will quite commonly be displayed as fewer than the standard 8 chars, especially in "programming" editors and IDEs.

So in otherwords:

printf("%-8s%s", "foo", "bar"); /* this will ALWAYS output "foo     bar" */
printf("foo\tbar"); /* who knows how this will be rendered */

IMHO, tabs in general are rarely appropriate for anything. An exception might be generating output for a program that requires tab-separated-value input files (similar to comma separated value).

Backspace '\b' is a different story... it should never be used to create a text file since it will just make a text editor spit out garbage. But it does have many applications in writing interactive command line programs that cannot be accomplished with format strings alone. If you find yourself needing it a lot, check out "ncurses", which gives you much better control over where your output goes on the terminal screen. And typically, since it's 2011 and not 1995, a GUI is usually easier to deal with for highly interactive programs. But again, there are exceptions. Like writing a telnet server or console for a new scripting language.

Which version of CodeIgniter am I currently using?

You should try :

<?php
echo CI_VERSION;
?>

Or check the file system/core/CodeIgniter.php

Determine Whether Two Date Ranges Overlap

I found another quite simple approach. If start and end date of daterange1 falls before start date of daterange2 or start and end date of daterange1 falls after end date of daterange2 this means they don't intersect with each other.

public boolean doesIntersect(DateRangeModel daterange1, DateRangeModel  daterange2) {
    return !(
            (daterange1.getStartDate().isBefore(daterange2.getStartDate())
                    && daterange1.getEndDate().isBefore(daterange2.getStartDate())) ||
                    (daterange1.getStartDate().isAfter(daterange2.getStartDate())
                            && daterange1.getEndDate().isAfter(daterange2.getEndDate())));
}

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

If you need it to work in IE7, you can't use the undocumented, buggy, and unsupported {'width':'auto'} option. Instead, add the following to your .dialog():

'open': function(){ $(this).dialog('option', 'width', this.scrollWidth) }

Whether .scrollWidth includes the right-side padding depends on the browser (Firefox differs from Chrome), so you can either add a subjective "good enough" number of pixels to .scrollWidth, or replace it with your own width-calculation function.

You might want to include width: 0 among your .dialog() options, since this method will never decrease the width, only increase it.

Tested to work in IE7, IE8, IE9, IE10, IE11, Firefox 30, Chrome 35, and Opera 22.

Compare two objects with .equals() and == operator

Here the output will be false , false beacuse in first sopln statement you are trying to compare a string type varible of Myclass type to the other MyClass type and it will allow because of both are Object type and you have used "==" oprerator which will check the reference variable value holding the actual memory not the actual contnets inside the memory . In the second sopln also it is the same as you are again calling a.equals(object2) where a is a varible inside object1 . Do let me know your findings on this .

HTML-encoding lost when attribute read from input field

Here's a little bit that emulates the Server.HTMLEncode function from Microsoft's ASP, written in pure JavaScript:

_x000D_
_x000D_
function htmlEncode(s) {_x000D_
  var ntable = {_x000D_
    "&": "amp",_x000D_
    "<": "lt",_x000D_
    ">": "gt",_x000D_
    "\"": "quot"_x000D_
  };_x000D_
  s = s.replace(/[&<>"]/g, function(ch) {_x000D_
    return "&" + ntable[ch] + ";";_x000D_
  })_x000D_
  s = s.replace(/[^ -\x7e]/g, function(ch) {_x000D_
    return "&#" + ch.charCodeAt(0).toString() + ";";_x000D_
  });_x000D_
  return s;_x000D_
}
_x000D_
_x000D_
_x000D_

The result does not encode apostrophes, but encodes the other HTML specials and any character outside the 0x20-0x7e range.

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

How to select the row with the maximum value in each group

One more base R solution:

merge(aggregate(pt ~ Subject, max, data = group), group)

  Subject pt Event
1       1  5     2
2       2 17     2
3       3  5     2

Regular vs Context Free Grammars

A grammar is context-free if all production rules have the form: A (that is, the left side of a rule can only be a single variable; the right side is unrestricted and can be any sequence of terminals and variables). We can define a grammar as a 4-tuple where V is a finite set (variables), _ is a finite set (terminals), S is the start variable, and R is a finite set of rules, each of which is a mapping V
regular grammar is either right or left linear, whereas context free grammar is basically any combination of terminals and non-terminals. hence we can say that regular grammar is a subset of context-free grammar. After these properties we can say that Context Free Languages set also contains Regular Languages set

PHP error: "The zip extension and unzip command are both missing, skipping."

I got this error when I installed Laravel 5.5 on my digitalocean cloud server (Ubuntu 18.04 and PHP 7.2) and the following command fixed it.

sudo apt install zip unzip php7.2-zip

how to calculate binary search complexity

T(n)=T(n/2)+1

T(n/2)= T(n/4)+1+1

Put the value of The(n/2) in above so T(n)=T(n/4)+1+1 . . . . T(n/2^k)+1+1+1.....+1

=T(2^k/2^k)+1+1....+1 up to k

=T(1)+k

As we taken 2^k=n

K = log n

So Time complexity is O(log n)

Removing packages installed with go get

#!/bin/bash

goclean() {
 local pkg=$1; shift || return 1
 local ost
 local cnt
 local scr

 # Clean removes object files from package source directories (ignore error)
 go clean -i $pkg &>/dev/null

 # Set local variables
 [[ "$(uname -m)" == "x86_64" ]] \
 && ost="$(uname)";ost="${ost,,}_amd64" \
 && cnt="${pkg//[^\/]}"

 # Delete the source directory and compiled package directory(ies)
 if (("${#cnt}" == "2")); then
  rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
  rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
 elif (("${#cnt}" > "2")); then
  rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
  rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
 fi

 # Reload the current shell
 source ~/.bashrc
}

Usage:

# Either launch a new terminal and copy `goclean` into the current shell process, 
# or create a shell script and add it to the PATH to enable command invocation with bash.

goclean github.com/your-username/your-repository

Check if list contains element that contains a string and get that element

You should be able to use something like this, it has worked okay for me:

var valuesToMatch = yourList.Where(stringCheck => stringCheck.Contains(myString));

or something like this, if you need to look where it doesn't match.

 var valuesToMatch = yourList.Where(stringCheck => !stringCheck.Contains(myString));

Improve SQL Server query performance on large tables

Simple Answer: NO. You cannot help ad hoc queries on a 238 column table with a 50% Fill Factor on the Clustered Index.

Detailed Answer:

As I have stated in other answers on this topic, Index design is both Art and Science and there are so many factors to consider that there are few, if any, hard and fast rules. You need to consider: the volume of DML operations vs SELECTs, disk subsystem, other indexes / triggers on the table, distribution of data within the table, are queries using SARGable WHERE conditions, and several other things that I can't even remember right now.

I can say that no help can be given for questions on this topic without an understanding of the Table itself, its indexes, triggers, etc. Now that you have posted the table definition (still waiting on the Indexes but the Table definition alone points to 99% of the issue) I can offer some suggestions.

First, if the table definition is accurate (238 columns, 50% Fill Factor) then you can pretty much ignore the rest of the answers / advice here ;-). Sorry to be less-than-political here, but seriously, it's a wild goose chase without knowing the specifics. And now that we see the table definition it becomes quite a bit clearer as to why a simple query would take so long, even when the test queries (Update #1) ran so quickly.

The main problem here (and in many poor-performance situations) is bad data modeling. 238 columns is not prohibited just like having 999 indexes is not prohibited, but it is also generally not very wise.

Recommendations:

  1. First, this table really needs to be remodeled. If this is a data warehouse table then maybe, but if not then these fields really need to be broken up into several tables which can all have the same PK. You would have a master record table and the child tables are just dependent info based on commonly associated attributes and the PK of those tables is the same as the PK of the master table and hence also FK to the master table. There will be a 1-to-1 relationship between master and all child tables.
  2. The use of ANSI_PADDING OFF is disturbing, not to mention inconsistent within the table due to the various column additions over time. Not sure if you can fix that now, but ideally you would always have ANSI_PADDING ON, or at the very least have the same setting across all ALTER TABLE statements.
  3. Consider creating 2 additional File Groups: Tables and Indexes. It is best not to put your stuff in PRIMARY as that is where SQL SERVER stores all of its data and meta-data about your objects. You create your Table and Clustered Index (as that is the data for the table) on [Tables] and all Non-Clustered indexes on [Indexes]
  4. Increase the Fill Factor from 50%. This low number is likely why your index space is larger than your data space. Doing an Index Rebuild will recreate the data pages with a max of 4k (out of the total 8k page size) used for your data so your table is spread out over a wide area.
  5. If most or all queries have "ER101_ORG_CODE" in the WHERE condition, then consider moving that to the leading column of the clustered index. Assuming that it is used more often than "ER101_ORD_NBR". If "ER101_ORD_NBR" is used more often then keep it. It just seems, assuming that the field names mean "OrganizationCode" and "OrderNumber", that "OrgCode" is a better grouping that might have multiple "OrderNumbers" within it.
  6. Minor point, but if "ER101_ORG_CODE" is always 2 characters, then use CHAR(2) instead of VARCHAR(2) as it will save a byte in the row header which tracks variable width sizes and adds up over millions of rows.
  7. As others here have mentioned, using SELECT * will hurt performance. Not only due to it requiring SQL Server to return all columns and hence be more likely to do a Clustered Index Scan regardless of your other indexes, but it also takes SQL Server time to go to the table definition and translate * into all of the column names. It should be slightly faster to specify all 238 column names in the SELECT list though that won't help the Scan issue. But do you ever really need all 238 columns at the same time anyway?

Good luck!

UPDATE
For the sake of completeness to the question "how to improve performance on a large table for ad-hoc queries", it should be noted that while it will not help for this specific case, IF someone is using SQL Server 2012 (or newer when that time comes) and IF the table is not being updated, then using Columnstore Indexes is an option. For more details on that new feature, look here: http://msdn.microsoft.com/en-us/library/gg492088.aspx (I believe these were made to be updateable starting in SQL Server 2014).

UPDATE 2
Additional considerations are:

  • Enable compression on the Clustered Index. This option became available in SQL Server 2008, but as an Enterprise Edition-only feature. However, as of SQL Server 2016 SP1, Data Compression was made available in all editions! Please see the MSDN page for Data Compression for details on Row and Page Compression.
  • If you cannot use Data Compression, or if it won't provide much benefit for a particular table, then IF you have a column of a fixed-length type (INT, BIGINT, TINYINT, SMALLINT, CHAR, NCHAR, BINARY, DATETIME, SMALLDATETIME, MONEY, etc) and well over 50% of the rows are NULL, then consider enabling the SPARSE option which became available in SQL Server 2008. Please see the MSDN page for Use Sparse Columns for details.

How do I concatenate strings in Swift?

Several words about performance

UI Testing Bundle on iPhone 7(real device) with iOS 14

var result = ""
for i in 0...count {
    <concat_operation>
}

Count = 5_000

//Append
result.append(String(i))                         //0.007s 39.322kB

//Plus Equal
result += String(i)                              //0.006s 19.661kB

//Plus
result = result + String(i)                      //0.130s 36.045kB

//Interpolation
result = "\(result)\(i)"                         //0.164s 16.384kB

//NSString
result = NSString(format: "%@%i", result, i)     //0.354s 108.142kB

//NSMutableString
result.append(String(i))                         //0.008s 19.661kB

Disable next tests:

  • Plus up to 100_000 ~10s
  • interpolation up to 100_000 ~10s
  • NSString up to 10_000 -> memory issues

Count = 1_000_000

//Append
result.append(String(i))                         //0.566s 5894.979kB

//Plus Equal
result += String(i)                              //0.570s 5894.979kB

//NSMutableString
result.append(String(i))                         //0.751s 5891.694kB

*Note about Convert Int to String

Source code

import XCTest

class StringTests: XCTestCase {

    let count = 1_000_000
    
    let metrics: [XCTMetric] = [
        XCTClockMetric(),
        XCTMemoryMetric()
    ]
    
    let measureOptions = XCTMeasureOptions.default

    
    override func setUp() {
        measureOptions.iterationCount = 5
    }
    
    func testAppend() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result.append(String(i))
            }
        }

    }
    
    func testPlusEqual() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result += String(i)
            }
        }
    }
    
    func testPlus() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result = result + String(i)
            }
        }
    }
    
    func testInterpolation() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result = "\(result)\(i)"
            }
        }
    }
    
    //Up to 10_000
    func testNSString() {
        var result: NSString =  ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result = NSString(format: "%@%i", result, i)
            }
        }
    }
    
    func testNSMutableString() {
        let result = NSMutableString()
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result.append(String(i))
            }
        }
    }

}

Bootstrap: change background color

You can target that div from your stylesheet in a number of ways.

Simply use

.col-md-6:first-child {
  background-color: blue;
}

Another way is to assign a class to one div and then apply the style to that class.

<div class="col-md-6 blue"></div>

.blue {
  background-color: blue;
}

There are also inline styles.

<div class="col-md-6" style="background-color: blue"></div>

Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary class from the section and add you custom class to the div.

_x000D_
_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
    <!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
      <div class="col-xs-6">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
      <div class="col-xs-6 blue">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Maven dependency for Servlet 3.0 API?

Try this code...

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>3.0-alpha-1</version>
    </dependency>

How can I get the domain name of my site within a Django template?

I know this question is old, but I stumbled upon it looking for a pythonic way to get current domain.

def myview(request):
    domain = request.build_absolute_uri('/')[:-1]
    # that will build the complete domain: http://foobar.com

Sql connection-string for localhost server

Data Source=HARIHARAN-PC\SQLEXPRESS; Initial Catalog=Your_DataBase_name; Integrated Security=true/false; User ID=your_Username;Password=your_Password;

To know more about connection string Click here

Regex for quoted string with escaping quotes

here is one that work with both " and ' and you easily add others at the start.

("|')(?:\\\1|[^\1])*?\1

it uses the backreference (\1) match exactley what is in the first group (" or ').

http://www.regular-expressions.info/backref.html

How to implement a binary tree?

Simple implementation of BST in Python

class TreeNode:
    def __init__(self, value):
        self.left = None
        self.right = None
        self.data = value

class Tree:
    def __init__(self):
        self.root = None

    def addNode(self, node, value):
        if(node==None):
            self.root = TreeNode(value)
        else:
            if(value<node.data):
                if(node.left==None):
                    node.left = TreeNode(value)
                else:
                    self.addNode(node.left, value)
            else:
                if(node.right==None):
                    node.right = TreeNode(value)
                else:
                    self.addNode(node.right, value)

    def printInorder(self, node):
        if(node!=None):
            self.printInorder(node.left)
            print(node.data)
            self.printInorder(node.right)

def main():
    testTree = Tree()
    testTree.addNode(testTree.root, 200)
    testTree.addNode(testTree.root, 300)
    testTree.addNode(testTree.root, 100)
    testTree.addNode(testTree.root, 30)
    testTree.printInorder(testTree.root)

How to suppress warnings globally in an R Script

I have replaced the printf calls with calls to warning in the C-code now. It will be effective in the version 2.17.2 which should be available tomorrow night. Then you should be able to avoid the warnings with suppressWarnings() or any of the other above mentioned methods.

suppressWarnings({ your code })

How to change Label Value using javascript

Try

use an id for hidden field and use id of checkbox in javascript.

and change the ClientIDMode="static" too

<input type="hidden" ClientIDMode="static" id="label1" name="label206451" value="0" />

   <script type="text/javascript"> 
    var cb = document.getElementById('txt206451');
    var label = document.getElementById('label1');
    cb.addEventListener('click',function(evt){
    if(cb.checked){
        label.value='Thanks'
    }else{
        label.value='0'
    }
    },false);
    </script>

how to install gcc on windows 7 machine?

I use msysgit to install gcc on Windows, it has a nice installer which installs most everything that you might need. Most devs will need more than just the compiler, e.g. the shell, shell tools, make, git, svn, etc. msysgit comes with all of that. https://msysgit.github.io/

edit: I am now using msys2. Msys2 uses pacman from Arch Linux to install packages, and includes three environments, for building msys2 apps, 32-bit native apps, and 64-bit native apps. (You probably want to build 32-bit native apps.)

https://msys2.github.io/

You could also go full-monty and install code::blocks or some other gui editor that comes with a compiler. I prefer to use vim and make.

Add one day to date in javascript

The Date constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.

Date.getDate() returns the day index for the current date object. In your example, the day is 30. The final expression is 31, therefore it's returning 31 milliseconds after December 31st, 1969.

A simple solution using your existing approach is to use Date.getTime() instead. Then, add a days worth of milliseconds instead of 1.

For example,

var dateString = 'Mon Jun 30 2014 00:00:00';

var startDate = new Date(dateString);

// seconds * minutes * hours * milliseconds = 1 day 
var day = 60 * 60 * 24 * 1000;

var endDate = new Date(startDate.getTime() + day);

JSFiddle

Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.

MySQL: Enable LOAD DATA LOCAL INFILE

in case your flavor of mysql on ubuntu does NOT under any circumstances work and you still get the 1148 error, you can run the load data infile command via command line

open a terminal window

run mysql -u YOURUSERNAME -p --local-infile YOURDBNAME

you will be requested to insert mysqluser password

you will be running MySQLMonitor and your command prompt will be mysql>

run your load data infile command (dont forget to end with a semicolon ; )

like this:

load data local infile '/home/tony/Desktop/2013Mini.csv' into table Reading_Table FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

how to get the one entry from hashmap without iterating

The answer by Jesper is good. An other solution is to use TreeMap (you asked for other data structures).

TreeMap<String, String> myMap = new TreeMap<String, String>();
String first = myMap.firstEntry().getValue();
String firstOther = myMap.get(myMap.firstKey());

TreeMap has an overhead so HashMap is faster, but just as an example of an alternative solution.

How to display UTF-8 characters in phpMyAdmin?

Change latin1_swedish_ci to utf8_general_ci in phpmyadmin->table_name->field_name

This is where you find it on the screen:

No newline at end of file

There is one thing that I don't see in previous responses. Warning about no end-of-line could be a warning when a portion of a file has been truncated. It could be a symptom of missing data.

Chrome:The website uses HSTS. Network errors...this page will probably work later

I recently had the same issue while trying to access domains using CloudFlare Origin CA.

The only way I found to workaround/avoid HSTS cert exception on Chrome (Windows build) was following the short instructions in https://support.opendns.com/entries/66657664.

The workaround:
Add to Chrome shortcut the flag --ignore-certificate-errors, then reopen it and surf to your website.

Reminder:
Use it only for development purposes.

enter image description here

Quickly create large file on a Windows system

fsutil file createnew <filename> <length>

where <length> is in bytes.

For example, to create a 1MB (Windows MB or MiB) file named 'test', this code can be used.

fsutil file createnew test 1048576

fsutil requires administrative privileges though.

Is it possible to ping a server from Javascript?

you can try this:

put ping.html on the server with or without any content, on the javascript do same as below:

<script>
    function ping(){
       $.ajax({
          url: 'ping.html',
          success: function(result){
             alert('reply');
          },     
          error: function(result){
              alert('timeout/error');
          }
       });
    }
</script>

How do I concatenate or merge arrays in Swift?

To complete the list of possible alternatives, reduce could be used to implement the behavior of flatten:

var a = ["a", "b", "c"] 
var b = ["d", "e", "f"]

let res = [a, b].reduce([],combine:+)

The best alternative (performance/memory-wise) among the ones presented is simply flatten, that just wrap the original arrays lazily without creating a new array structure.

But notice that flatten does not return a LazyCollection, so that lazy behavior will not be propagated to the next operation along the chain (map, flatMap, filter, etc...).

If lazyness makes sense in your particular case, just remember to prepend or append a .lazy to flatten(), for example, modifying Tomasz sample this way:

let c = [a, b].lazy.flatten()

How to quickly edit values in table in SQL Server Management Studio?

Go to Tools > Options. In the tree on the left, select SQL Server Object Explorer. Set the option "Value for Edit Top Rows command" to 0. It'll now allow you to view and edit the entire table from the context menu.

How to programmatically clear application data

This solution has really helped me :

By using below two methods we can clear data programatically

    public void clearApplicationData() {
    File cacheDirectory = getCacheDir();
    File applicationDirectory = new File(cacheDirectory.getParent());
    if (applicationDirectory.exists()) {
    String[] fileNames = applicationDirectory.list();
        for (String fileName : fileNames) {
            if (!fileName.equals("lib")) {
                deleteFile(new File(applicationDirectory, fileName));
            }
        }
    }
}
    public static boolean deleteFile(File file) {
    boolean deletedAll = true;
    if (file != null) {
        if (file.isDirectory()) {
            String[] children = file.list();
            for (int i = 0; i < children.length; i++) {
                deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
            }
        } else {
            deletedAll = file.delete();
        }
    }

    return deletedAll;
}

Jquery validation plugin - TypeError: $(...).validate is not a function

You didn't include the base jQuery Validation library:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>

Put that before the additional methods library. (BTW this is a hosted version, download your own if you want)

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

How to move files from one git repo to another (not a clone), preserving history

In my case, I didn't need to preserve the repo I was migrating from or preserve any previous history. I had a patch of the same branch, from a different remote

#Source directory
git remote rm origin
#Target directory
git remote add branch-name-from-old-repo ../source_directory

In those two steps, I was able to get the other repo's branch to appear in the same repo.

Finally, I set this branch (that I imported from the other repo) to follow the target repo's mainline (so I could diff them accurately)

git br --set-upstream-to=origin/mainline

Now it behaved as-if it was just another branch I had pushed against that same repo.

How to generate .json file with PHP?

Here is a sample code:

<?php 
$sql="select * from Posts limit 20"; 

$response = array();
$posts = array();
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) { 
  $title=$row['title']; 
  $url=$row['url']; 

  $posts[] = array('title'=> $title, 'url'=> $url);
} 

$response['posts'] = $posts;

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);


?> 

How to find the Vagrant IP?

I've developed a small vagrant-address plugin for that. It's simple, cross-platform, cross-provider, and does not require scripting.

https://github.com/mkuzmin/vagrant-address

What port number does SOAP use?

There is no such thing as "SOAP protocol". SOAP is an XML schema.

It usually runs over HTTP (port 80), however.

Stacked bar chart

You need to transform your data to long format and shouldn't use $ inside aes:

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

How to generate unique id in MySQL?

To get unique and random looking tokens you could just encrypt your primary key i.e.:

SELECT HEX(AES_ENCRYPT(your_pk,'your_password')) AS 'token' FROM your_table;

This is good enough plus its reversable so you'd not have to store that token in your table but to generate it instead.

Another advantage is once you decode your PK from that token you do not have to do heavy full text searches over your table but simple and quick PK search.

Theres one small problem though. MySql supports different block encryption modes which if changed will completely change your token space making old tokens useless...

To overcome this one could set that variable before token generated i.e.:

SET block_encryption_mode = 'aes-256-cbc';

However that a bit waste... The solution for this is to attach an encryption mode used marker to the token:

SELECT CONCAT(CONV(CRC32(@@GLOBAL.block_encryption_mode),10,35),'Z',HEX(AES_ENCRYPT(your_pk,'your_password'))) AS 'token' FROM your_table;

Another problem may come up if you wish to persist that token in your table on INSERT because to generate it you need to know primary_key for the record which was not inserted yet... Ofcourse you might just INSERT and then UPDATE with LAST_INSERT_ID() but again - theres a better solution:

INSERT INTO your_table ( token )
SELECT CONCAT(CONV(CRC32(@@GLOBAL.block_encryption_mode),10,35),'Z',HEX(AES_ENCRYPT(your_pk,'your_password'))) AS 'token'
FROM information_schema.TABLES 
WHERE  TABLE_SCHEMA = DATABASE() AND TABLE_NAME = "your_table";

One last but not least advantage of this solution is you can easily replicate it in php, python, js or any other language you might use.

How to override trait function and call it from the overridden function?

Your last one was almost there:

trait A {
    function calc($v) {
        return $v+1;
    }
}

class MyClass {
    use A {
        calc as protected traitcalc;
    }

    function calc($v) {
        $v++;
        return $this->traitcalc($v);
    }
}

The trait is not a class. You can't access its members directly. It's basically just automated copy and paste...

How to compare binary files to check if they are the same?

There is a relatively simple way to check if two binary files are the same.

If you use file input/output in a programming language; you can store each bit of both the binary files into their own arrays.

At this point the check is as simple as :

if(file1 != file2){
    //do this
}else{
    /do that
}

How to find the statistical mode?

R has so many add-on packages that some of them may well provide the [statistical] mode of a numeric list/series/vector.

However the standard library of R itself doesn't seem to have such a built-in method! One way to work around this is to use some construct like the following (and to turn this to a function if you use often...):

mySamples <- c(19, 4, 5, 7, 29, 19, 29, 13, 25, 19)
tabSmpl<-tabulate(mySamples)
SmplMode<-which(tabSmpl== max(tabSmpl))
if(sum(tabSmpl == max(tabSmpl))>1) SmplMode<-NA
> SmplMode
[1] 19

For bigger sample list, one should consider using a temporary variable for the max(tabSmpl) value (I don't know that R would automatically optimize this)

Reference: see "How about median and mode?" in this KickStarting R lesson
This seems to confirm that (at least as of the writing of this lesson) there isn't a mode function in R (well... mode() as you found out is used for asserting the type of variables).

How to get file name when user select a file via <input type="file" />?

I'll answer this question via Simple Javascript that is supported in all browsers that I have tested so far (IE8 to IE11, Chrome, FF etc).

Here is the code.

_x000D_
_x000D_
function GetFileSizeNameAndType()_x000D_
        {_x000D_
        var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE._x000D_
_x000D_
        var totalFileSize = 0;_x000D_
_x000D_
        // VALIDATE OR CHECK IF ANY FILE IS SELECTED._x000D_
        if (fi.files.length > 0)_x000D_
        {_x000D_
            // RUN A LOOP TO CHECK EACH SELECTED FILE._x000D_
            for (var i = 0; i <= fi.files.length - 1; i++)_x000D_
            {_x000D_
                //ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE_x000D_
                var fsize = fi.files.item(i).size;_x000D_
                totalFileSize = totalFileSize + fsize;_x000D_
                document.getElementById('fp').innerHTML =_x000D_
                document.getElementById('fp').innerHTML_x000D_
                +_x000D_
                '<br /> ' + 'File Name is <b>' + fi.files.item(i).name_x000D_
                +_x000D_
                '</b> and Size is <b>' + Math.round((fsize / 1024)) //DEFAULT SIZE IS IN BYTES SO WE DIVIDING BY 1024 TO CONVERT IT IN KB_x000D_
                +_x000D_
                '</b> KB and File Type is <b>' + fi.files.item(i).type + "</b>.";_x000D_
            }_x000D_
        }_x000D_
        document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";_x000D_
    }
_x000D_
    <p>_x000D_
        <input type="file" id="file" multiple onchange="GetFileSizeNameAndType()" />_x000D_
    </p>_x000D_
_x000D_
    <div id="fp"></div>_x000D_
    <p>_x000D_
        <div id="divTotalSize"></div>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

*Please note that we are displaying filesize in KB (Kilobytes). To get in MB divide it by 1024 * 1024 and so on*.

It'll perform file outputs like these on selecting Snapshot of a sample output of this code

How to sum digits of an integer in java?

It might be too late, but I see that many solutions posted here use O(n^2) time complexity, this is okay for small inputs, but as you go ahead with large inputs, you might want to reduce time complexity. Here is something which I worked on to do the same in linear time complexity.

NOTE : The second solution posted by Arunkumar is constant time complexity.

    private int getDigits(int num) {
    int sum =0;
    while(num > 0) { //num consists of 2 digits max, hence O(1) operation
        sum = sum + num % 10;
        num = num / 10;
    }   
    return sum;
}
public int addDigits(int N) {
    int temp1=0, temp2= 0;
    while(N > 0) {
        temp1= N % 10;
        temp2= temp1 + temp2;
        temp2= getDigits(temp2); // this is O(1) operation
        N = N/ 10;
    }
    return temp2;
}   

Please ignore my variable naming convention, I know it is not ideal. Let me explain the code with sample input , e.g. "12345". Output must be 6, in a single traversal.

Basically what I am doing is that I go from LSB to MSB , and add digits of the sum found, in every iteration.

The values look like this

Initially temp1 = temp2 = 0

N     | temp1 ( N % 10)  | temp2 ( temp1 + temp2 )
12345 | 5                | 5   
1234  | 4                | 5 + 4 = 9 ( getDigits(9) = 9)
123   | 3                | 9 + 3 = 12 = 3 (getDigits(12) =3 )
12    | 2                | 3 + 2 = 5 (getDigits(5) = 5)
1     | 1                | 5 + 1 = 6 (getDigits(6) = 6 )

Answer is 6, and we avoided one extra loop. I hope it helps.

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

Use SET STATISTICS TIME ON

above your query.

Below near result tab you can see a message tab. There you can see the time.

JavaScript: Difference between .forEach() and .map()

The difference lies in what they return. After execution:

arr.map()

returns an array of elements resulting from the processed function; while:

arr.forEach()

returns undefined.

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

What is the difference between precision and scale?

precision: Its the total number of digits before or after the radix point. EX: 123.456 here precision is 6.

Scale: Its the total number of digits after the radix point. EX: 123.456 here Scaleis 3

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

Angular : Manual redirect to route

Try this:

constructor(  public router: Router,) {
  this.route.params.subscribe(params => this._onRouteGetParams(params));
}
this.router.navigate(['otherRoute']);

Serializing list to JSON

Yes, but then what do you do about the django objects? simple json tends to choke on them.

If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

seralized_dict = simplejson.dumps(my_dict, 
                     default=lambda a: "[%s,%s]" % (str(type(a)), a.pk)
                     )

to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.

How do I change a TCP socket to be non-blocking?

I know it's an old question, but for everyone on google ending up here looking for information on how to deal with blocking and non-blocking sockets here is an in depth explanation of the different ways how to deal with the I/O modes of sockets - http://dwise1.net/pgm/sockets/blocking.html.

Quick summary:

  • So Why do Sockets Block?

  • What are the Basic Programming Techniques for Dealing with Blocking Sockets?

    • Have a design that doesn't care about blocking
    • Using select
    • Using non-blocking sockets.
    • Using multithreading or multitasking

Android turn On/Off WiFi HotSpot programmatically

APManager - Access Point Manager

Step 1 : Add the jcenter repository to your build file
allprojects {
    repositories {
        ...
        jcenter()
    }
}
Step 2 : Add the dependency
dependencies {
    implementation 'com.vkpapps.wifimanager:APManager:1.0.0'
}
Step 3 use in your app
APManager apManager = APManager.getApManager(this);
apManager.turnOnHotspot(this, new APManager.OnSuccessListener() {

    @Override
    public void onSuccess(String ssid, String password) {
        //write your logic
    }

}, new APManager.OnFailureListener() {

    @Override
    public void onFailure(int failureCode, @Nullable Exception e) {
        //handle error like give access to location permission,write system setting permission,
        //disconnect wifi,turn off already created hotspot,enable GPS provider
        
        //or use DefaultFailureListener class to handle automatically
    }

});

check out source code https://github.com/vijaypatidar/AndroidWifiManager

load scripts asynchronously

Here is a great contemporary solution to the asynchronous script loading though it only address the js script with async false.

There is a great article written in www.html5rocks.com - Deep dive into the murky waters of script loading .

After considering many possible solutions, the author concluded that adding js scripts to the end of body element is the best possible way to avoid blocking page rendering by js scripts.

In the mean time, the author added another good alternate solution for those people who are desperate to load and execute scripts asynchronously.

Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:

[
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
].forEach(function(src) {
  var script = document.createElement('script');
  script.src = src;
  script.async = false;
  document.head.appendChild(script);
});

Now, Spec says: Download together, execute in order as soon as all download.

Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.

Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.

IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.

Everything else says: I’m your friend, we’re going to do this by the book.

Now, the full code with IE < 10 workaround:

var scripts = [
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
];
var src;
var script;
var pendingScripts = [];
var firstScript = document.scripts[0];

// Watch scripts load in IE
function stateChange() {
  // Execute as many scripts in order as we can
  var pendingScript;
  while (pendingScripts[0] && ( pendingScripts[0].readyState == 'loaded' || pendingScripts[0].readyState == 'complete' ) ) {
    pendingScript = pendingScripts.shift();
    // avoid future loading events from this script (eg, if src changes)
    pendingScript.onreadystatechange = null;
    // can't just appendChild, old IE bug if element isn't closed
    firstScript.parentNode.insertBefore(pendingScript, firstScript);
  }
}

// loop through our script urls
while (src = scripts.shift()) {
  if ('async' in firstScript) { // modern browsers
    script = document.createElement('script');
    script.async = false;
    script.src = src;
    document.head.appendChild(script);
  }
  else if (firstScript.readyState) { // IE<10
    // create a script and add it to our todo pile
    script = document.createElement('script');
    pendingScripts.push(script);
    // listen for state changes
    script.onreadystatechange = stateChange;
    // must set src AFTER adding onreadystatechange listener
    // else we’ll miss the loaded event for cached scripts
    script.src = src;
  }
  else { // fall back to defer
    document.write('<script src="' + src + '" defer></'+'script>');
  }
}

How to get Locale from its String representation in Java?

  1. Java provides lot of things with proper implementation lot of complexity can be avoided. This returns ms_MY.

    String key = "ms-MY";
    Locale locale = new Locale.Builder().setLanguageTag(key).build();
    
  2. Apache Commons has LocaleUtils to help parse a string representation. This will return en_US

    String str = "en-US";
    Locale locale =  LocaleUtils.toLocale(str);
    System.out.println(locale.toString());
    
  3. You can also use locale constructors.

    // Construct a locale from a language code.(eg: en)
    new Locale(String language)
    // Construct a locale from language and country.(eg: en and US)
    new Locale(String language, String country)
    // Construct a locale from language, country and variant.
    new Locale(String language, String country, String variant)
    

Please check this LocaleUtils and this Locale to explore more methods.

Error: 'int' object is not subscriptable - Python

name1 = input("What's your name? ")
age1 = int(input ("how old are you? "))
twentyone = str(21 - int(age1))

if age1<21:
    print ("Hi, " + name1+ " you will be 21 in: " + twentyone + " years.")

else:
    print("You are over the age of 21")

How to set time to midnight for current day?

Only need to set it to

DateTime.Now.Date

Console.WriteLine(DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Console.Read();

It shows

"2017-04-08 00:00:00"

on my machine.

Swap DIV position with CSS only

This solution worked for me:

Using a parent element like:

.parent-div {
    display:flex;
    flex-direction: column-reverse;
}

In my case I didn't have to change the css of the elements that I needed to switch.

Enabling/Disabling Microsoft Virtual WiFi Miniport

In my case I had to uninstall and reinstall the wireless adapter driver to be able to execute the command

count (non-blank) lines-of-code in bash

rgrep . | wc -l

gives the count of non blank lines in the current working directory.

Update multiple rows with different values in a single SQL query

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

You could do:

 UPDATE table SET posX=CASE
      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ...
      ELSE posX END, posY = CASE ... END
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

Otherwise, I'd try with indexing on id, or modifying the architecture.

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

Adding click event handler to iframe

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

How to use classes from .jar files?

You need to add the jar file in the classpath. To compile your java class:

javac -cp .;jwitter.jar MyClass.java

To run your code (provided that MyClass contains a main method):

java -cp .;jwitter.jar MyClass

You can have the jar file anywhere. The above work if the jar file is in the same directory as your java file.

Replace \n with <br />

To handle many newline delimiters, including character combinations like \r\n, use splitlines (see this related post) use the following:

'<br />'.join(thatLine.splitlines())

Python read JSON file and modify

try this script:

with open("data.json") as f:
    data = json.load(f)
    data["id"] = 134
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "name":"mynamme",
    "id":134
}

Just the arrangement is different, You can solve the problem by converting the "data" type to a list, then arranging it as you wish, then returning it and saving the file, like that:

index_add = 0
with open("data.json") as f:
    data = json.load(f)
    data_li = [[k, v] for k, v in data.items()]
    data_li.insert(index_add, ["id", 134])
    data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "id":134,
    "name":"myname"
}

you can add if condition in order not to repeat the key, just change it, like that:

index_add = 0
n_k = "id"
n_v = 134
with open("data.json") as f:
    data = json.load(f)
    if n_k in data:
        data[n_k] = n_v
    else:
       data_li = [[k, v] for k, v in data.items()]
       data_li.insert(index_add, [n_k, n_v])
       data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

PL/SQL: numeric or value error: character string buffer too small

is due to the fact that you declare a string to be of a fixed length (say 20), and at some point in your code you assign it a value whose length exceeds what you declared.

for example:

myString VARCHAR2(20);
myString :='abcdefghijklmnopqrstuvwxyz'; --length 26

will fire such an error

Return None if Dictionary key is not available

You can use dict.get()

value = d.get(key)

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None:

value = d.get(key, "empty")

Failed to resolve version for org.apache.maven.archetypes

Create New User Environment Variables:

MAVEN_HOME=D:\apache-maven-3.5.3

MAVEN=D:\apache-maven-3.5.3\bin

MAVEN_OPTS=-Xms256m -Xmx512m

Appened below in Path variable (System Variable):

;D:\apache-maven-3.5.3\bin;

Why are there two ways to unstage a file in Git?

It would seem to me that git rm --cached <file> removes the file from the index without removing it from the directory where a plain git rm <file> would do both, just as an OS rm <file> would remove the file from the directory without removing its versioning.

What range of values can integer types store in C++

No, only part of ten digits number can be stored in a unsigned long int whose valid range is 0 to 4,294,967,295 . you can refer to this: http://msdn.microsoft.com/en-us/library/s3f49ktz(VS.80).aspx

How to prevent line breaks in list items using CSS

display: inline-block; will prevent break between the words in a list item

 li {
    display: inline-block;
 }

Spring Boot War deployed to Tomcat

I think you're confused by different paradigms here. First, war files and server deployment -- those things belong to Java Enterprise Edition (Java EE). These concepts have no real place in a spring-boot application, which follows a different model.

Spring-boot is responsible for creating an embedded container and running your services within it directly from standard jar files (although it can do a lot more). I think the intent of this model is to support micro-service development -- where each service has its own container and is completely self contained. You can use your code to generate Java EE apps too, but that would be silly considering that spring-boot is a lot easier (for certain types of application/service).

So, given this information you now have to decide what paradigm you're going to follow, and you need to follow that and only that.

Spring-boot is executable -- you just have to run the main method in the App class which you can do from the command line or using your favourite IDE or maven or gradle (tip: maven is the right answer). This will bring up a tomcat server (by default) and your service will be available within it. Given the configuration you posted above your service should be available at: http://localhost:7777/context/help -- the context is meant to be replaced with your context name, which you haven't shared.

You aren't meant to be creating a war, running tomcat, or deploying anything. None of that is necessary in spring-boot. The packaging in your pom should be jar, not war and the scope of the spring-boot-starter-tomcat should be removed -- it certainly isn't provided.

When you run your main method, the console output should tell you the context that you've registered; use that to get the URL right.

Having said all that, spring-boot has to exist in a JEE world for now (until it is widely adopted). For that reason, the spring people have documented an approach to building a war rather than an executable jar, for deployment to a servlet or JEE container. This allows a lot of the spring-boot tech to be used in environments where there are restrictions against using anything but wars (or ears). However, this is a just a response to the fact that such environments are quite common, and is not seen as a necessary, or even desirable, part of the solution.

How do I calculate the date in JavaScript three months prior to today?

There is an elegant answer already but I find that its hard to read so I made my own function. For my purposes I didn't need a negative result but it wouldn't be hard to modify.

    var subtractMonths = function (date1,date2) {
        if (date1-date2 <=0) {
            return 0;
        }
        var monthCount = 0;
        while (date1 > date2){
            monthCount++;
            date1.setMonth(date1.getMonth() -1);
        }
        return monthCount;
    }

How can I see function arguments in IPython Notebook Server 3?

In 1.0, the functionality was bound to ( and tab and shift-tab, in 2.0 tab was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab. ( was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab.

So press Shift-Tab.

Unstaged changes left after git reset --hard

try to simply git restore .

That's what git says & it's working

OwinStartup not firing

I had a similar issue to this and clearing Temporary ASP.NET Files fixed it. Hope this helps someone.

How to send file contents as body entity using cURL

I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:

curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX

How to generate unique ID with node.js

used https://www.npmjs.com/package/uniqid in npm

npm i uniqid

It will always create unique id's based on the current time, process and machine name.

  • With the current time the ID's are always unique in a single process.
  • With the Process ID the ID's are unique even if called at the same time from multiple processes.
  • With the MAC Address the ID's are unique even if called at the same time from multiple machines and processes.

Features:-

  • Very fast
  • Generates unique id's on multiple processes and machines even if called at the same time.
  • Shorter 8 and 12 byte versions with less uniqueness.

How to write character & in android strings.xml

For special character I normally use the Unicode definition, for the '&' for example: \u0026 if I am correct. Here is a nice reference page: http://jrgraphix.net/research/unicode_blocks.php?block=0

python catch exception and continue try block

I don't think you want to do this. The correct way to use a try statement in general is as precisely as possible. I think it would be better to do:

try:
    do_smth1()
except Stmnh1Exception:
    # handle Stmnh1Exception

try:
    do_smth2()
except Stmnh2Exception:
    # handle Stmnh2Exception

Printing integer variable and string on same line in SQL

You may try this one,

declare @Number INT = 5                            
print 'There are ' + CONVERT(VARCHAR, @Number) + ' alias combinations did not match a record'

How to grep Git commit diffs or contents for a certain word?

git log's pickaxe will find commits with changes including "word" with git log -Sword

The data-toggle attributes in Twitter Bootstrap

From the Bootstrap Docs:

<!--Activate a modal without writing JavaScript. Set data-toggle="modal" on a 
controller element, like a button, along with a data-target="#foo" or href="#foo" 
to target a specific modal to toggle.-->

<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>

Delete forked repo from GitHub

Just delete the forked repo from your GitHub account.

https://help.github.com/articles/deleting-a-repository/

  • If I go to admin panel on GitHub there's a delete option. If I delete it as the option above, will it make any effect in the original one or not?

It wont make any changes in the original one; cos, its your repo now.

What are the best use cases for Akka framework

We are using akka with its camel plugin to distribute our analysis and trending processing for twimpact.com. We have to process between 50 and 1000 messages per second. In addition to multi-node processing with camel it is also used to distribute work on a single processor to multiple workers for maximum performance. Works quite well, but requires some understanding of how to handle congestions.

Is there a quick change tabs function in Visual Studio Code?

Linux In current Vscode 1.44.1 version

we could use ctrl+pageup for next editor and ctrl+pagedown for previous editor.

If there is a need to change

ctrl+shift+p > Preferences:Open Keyboard Shortcuts.

search for

nextEditor

change if needed by clicking it.

How to clear Route Caching on server: Laravel 5.2.37

If you want to remove the routes cache on your server, remove this file:

bootstrap/cache/routes.php

And if you want to update it just run php artisan route:cache and upload the bootstrap/cache/routes.php to your server.

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A far more clear solution is to use the command netsh to change the IP (or setting it back to DHCP)

netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0

Where "Local Area Connection" is the name of the network adapter. You could find it in the windows Network Connections, sometimes it is simply named "Ethernet".

Here are two methods to set the IP and also to set the IP back to DHCP "Obtain an IP address automatically"

public bool SetIP(string networkInterfaceName, string ipAddress, string subnetMask, string gateway = null)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var ipInfo = ipProperties.UnicastAddresses.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork);
    var currentIPaddress = ipInfo.Address.ToString();
    var currentSubnetMask = ipInfo.IPv4Mask.ToString();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (!isDHCPenabled && currentIPaddress == ipAddress && currentSubnetMask == subnetMask)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" static {ipAddress} {subnetMask}" + (string.IsNullOrWhiteSpace(gateway) ? "" : $"{gateway} 1")) { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

public bool SetDHCP(string networkInterfaceName)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (isDHCPenabled)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" dhcp") { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

What's the difference between an argument and a parameter?

Always Remember that:- Arguments are passed while parameters are recieved.

How can I map True/False to 1/0 in a Pandas DataFrame?

You can use a transformation for your data frame:

df = pd.DataFrame(my_data condition)

transforming True/False in 1/0

df = df*1

jQuery event handlers always execute in order they were bound - any way around this?

Chris Chilvers' advice should be the first course of action but sometimes we're dealing with third party libraries that makes this challenging and requires us to do naughty things... which this is. IMO it's a crime of presumption similar to using !important in CSS.

Having said that, building on Anurag's answer, here are a few additions. These methods allow for multiple events (e.g. "keydown keyup paste"), arbitrary positioning of the handler and reordering after the fact.

$.fn.bindFirst = function (name, fn) {
    this.bindNth(name, fn, 0);
}

$.fn.bindNth(name, fn, index) {
    // Bind event normally.
    this.bind(name, fn);
    // Move to nth position.
    this.changeEventOrder(name, index);
};

$.fn.changeEventOrder = function (names, newIndex) {
    var that = this;
    // Allow for multiple events.
    $.each(names.split(' '), function (idx, name) {
        that.each(function () {
            var handlers = $._data(this, 'events')[name.split('.')[0]];
            // Validate requested position.
            newIndex = Math.min(newIndex, handlers.length - 1);
            handlers.splice(newIndex, 0, handlers.pop());
        });
    });
};

One could extrapolate on this with methods that would place a given handler before or after some other given handler.

JQuery - Call the jquery button click event based on name property

You have to use the jquery attribute selector. You can read more here:

http://api.jquery.com/attribute-equals-selector/

In your case it should be:

$('input[name="btnName"]')