SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The IIS inbound rules as shown in the question DO work. I had to clear the browser cache and add the following line in the top of my <head> section of the index.html page:

<base href="/myApplication/app/" />

This is because I have more than one application in localhost and so requests to other partials were being taken to localhost/app/view1 instead of localhost/myApplication/app/view1

Hopefully this helps someone!

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

Python Script Uploading files via FTP

You will most likely want to use the ftplib module for python

 import ftplib
 ftp = ftplib.FTP()
 host = "ftp.site.uk"
 port = 21
 ftp.connect(host, port)
 print (ftp.getwelcome())
 try:
      print ("Logging in...")
      ftp.login("yourusername", "yourpassword")
 except:
     "failed to login"

This logs you into an FTP server. What you do from there is up to you. Your question doesnt indicate any other operations that really need doing.

.toLowerCase not working, replacement function?

.toLowerCase function only exists on strings. You can call toString() on anything in javascript to get a string representation. Putting this all together:

var ans = 334;
var temp = ans.toString().toLowerCase();
alert(temp);

How to export data to an excel file using PHPExcel

If you've copied this directly, then:

->setCellValue('B2', Ackermann') 

should be

->setCellValue('B2', 'Ackermann') 

In answer to your question:

Get the data that you want from limesurvey, and use setCellValue() to store those data values in the cells where you want to store it.

The Quadratic.php example file in /Tests might help as a starting point: it takes data from an input form and sets it to cells in an Excel workbook.

EDIT

An extremely simplistic example:

// Create your database query
$query = "SELECT * FROM myDataTable";  

// Execute the database query
$result = mysql_query($query) or die(mysql_error());

// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel(); 
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0); 
// Initialise the Excel row number
$rowCount = 1; 
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){ 
    // Set cell An to the "name" column from the database (assuming you have a column called name)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']); 
    // Set cell Bn to the "age" column from the database (assuming you have a column called age)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']); 
    // Increment the Excel row counter
    $rowCount++; 
} 

// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx'); 

EDIT #2

Using your existing code as the basis

// Instantiate a new PHPExcel object 
$objPHPExcel = new PHPExcel();  
// Set the active Excel worksheet to sheet 0 
$objPHPExcel->setActiveSheetIndex(0);  
// Initialise the Excel row number 
$rowCount = 1;  

//start of printing column names as names of MySQL fields  
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)  
{
    $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
    $column++;
}
//end of adding column names  

//start while loop to get data  
$rowCount = 2;  
while($row = mysql_fetch_row($result))  
{  
    $column = 'A';
    for($j=1; $j<mysql_num_fields($result);$j++)  
    {  
        if(!isset($row[$j]))  
            $value = NULL;  
        elseif ($row[$j] != "")  
            $value = strip_tags($row[$j]);  
        else  
            $value = "";  

        $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
        $column++;
    }  
    $rowCount++;
} 


// Redirect output to a client’s web browser (Excel5) 
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment;filename="Limesurvey_Results.xls"'); 
header('Cache-Control: max-age=0'); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
$objWriter->save('php://output');

What does getActivity() mean?

Two likely definitions:

Oracle comparing timestamp with date

to_date format worked for me. Please consider the date formats: MON-, MM, ., -.

t.start_date >= to_date('14.11.2016 04:01:39', 'DD.MM.YYYY HH24:MI:SS')
t.start_date <=to_date('14.11.2016 04:10:07', 'DD.MM.YYYY HH24:MI:SS')

Responsive css background images

background:url("img/content-bg.jpg") no-repeat;
background-position:center; 
background-size:cover;

or

background-size:100%;

Changing the "tick frequency" on x or y axis in matplotlib?

In case anyone is interested in a general one-liner, simply get the current ticks and use it to set the new ticks by sampling every other tick.

ax.set_xticks(ax.get_xticks()[::2])

Understanding SQL Server LOCKS on SELECT queries

A SELECT in SQL Server will place a shared lock on a table row - and a second SELECT would also require a shared lock, and those are compatible with one another.

So no - one SELECT cannot block another SELECT.

What the WITH (NOLOCK) query hint is used for is to be able to read data that's in the process of being inserted (by another connection) and that hasn't been committed yet.

Without that query hint, a SELECT might be blocked reading a table by an ongoing INSERT (or UPDATE) statement that places an exclusive lock on rows (or possibly a whole table), until that operation's transaction has been committed (or rolled back).

Problem of the WITH (NOLOCK) hint is: you might be reading data rows that aren't going to be inserted at all, in the end (if the INSERT transaction is rolled back) - so your e.g. report might show data that's never really been committed to the database.

There's another query hint that might be useful - WITH (READPAST). This instructs the SELECT command to just skip any rows that it attempts to read and that are locked exclusively. The SELECT will not block, and it will not read any "dirty" un-committed data - but it might skip some rows, e.g. not show all your rows in the table.

Latest jQuery version on Google's CDN

If you wish to use jQuery CDN other than Google hosted jQuery library, you might consider using this and ensures uses the latest version of jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

Error: The 'brew link' step did not complete successfully

I also managed to mess up my NPM and installed packages between these Homebrew versions and no matter how many time I unlinked / linked and uninstalled / installed node it still didn't work.

As it turns out you have to remove NPM from the path otherwise Homebrew won't install it: https://github.com/mxcl/homebrew/blob/master/Library/Formula/node.rb#L117

Hope this will help someone with the same problem and save that hour or so I had to spend looking for the problem...

Only allow specific characters in textbox

You need to subscribe to the KeyDown event on the text box. Then something like this:

private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if (!char.IsControl(e.KeyChar) 
       && !char.IsDigit(e.KeyChar) 
       && e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-'
       && e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*' 
       && e.KeyChar != '/')
    {
        e.Handled = true;
        return;
    }
    e.Handled=false;
    return;
}

The important thing to know is that if you changed the Handled property to true, it will not process the keystroke. Setting it to false will.

Change background image opacity

Responding to an earlier comment, you can change the background by variable in the "container" example if the CSS is in your php page and not in the css style sheet.

$bgimage = '[some image url];
background-image: url('<?php echo $bgimage; ?>');

How to use subprocess popen Python

subprocess.Popen takes a list of arguments:

from subprocess import Popen, PIPE

process = Popen(['swfdump', '/tmp/filename.swf', '-d'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

There's even a section of the documentation devoted to helping users migrate from os.popen to subprocess.

How do I replace part of a string in PHP?

You need first to cut the string in how many pieces you want. Then replace the part that you want:

 $text = 'this is the test for string.';
 $text = substr($text, 0, 10);
 echo $text = str_replace(" ", "_", $text);

This will output:

this_is_th

Pandas: how to change all the values of a column?

You can do a column transformation by using apply

Define a clean function to remove the dollar and commas and convert your data to float.

def clean(x):
    x = x.replace("$", "").replace(",", "").replace(" ", "")
    return float(x)

Next, call it on your column like this.

data['Revenue'] = data['Revenue'].apply(clean)

Oracle: not a valid month

You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;

05/12/2015

Expand and collapse with angular js

I just wrote a simple zippy/collapsable using Angular using ng-show, ng-click and ng-init. Its implemented to one level but can be expanded to multiple levels easily.

Assign a boolean variable to ng-show and toggle it on click of header.

Check it out here enter image description here

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

How to make python Requests work via socks proxy

I installed pysocks and monkey patched create_connection in urllib3, like this:

import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "127.0.0.1", 1080)

def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                      source_address=None, socket_options=None):
    """Connect to *address* and return the socket object.

    Convenience function.  Connect to *address* (a 2-tuple ``(host,
    port)``) and return the socket object.  Passing the optional
    *timeout* parameter will set the timeout on the socket instance
    before attempting to connect.  If no *timeout* is supplied, the
    global default timeout setting returned by :func:`getdefaulttimeout`
    is used.  If *source_address* is set it must be a tuple of (host, port)
    for the socket to bind as a source address before making the connection.
    An host of '' or port 0 tells the OS to use the default.
    """

    host, port = address
    if host.startswith('['):
        host = host.strip('[]')
    err = None
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socks.socksocket(af, socktype, proto)

            # If provided, set socket level options before connecting.
            # This is the only addition urllib3 makes to this function.
            urllib3.util.connection._set_socket_options(sock, socket_options)

            if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
                sock.settimeout(timeout)
            if source_address:
                sock.bind(source_address)
            sock.connect(sa)
            return sock

        except socket.error as e:
            err = e
            if sock is not None:
                sock.close()
                sock = None

    if err is not None:
        raise err

    raise socket.error("getaddrinfo returns an empty list")

# monkeypatch
urllib3.util.connection.create_connection = create_connection

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

If you want to show/hide an element based on the status of one {{expression}} you can use ng-switch:

<p ng-switch="foo.bar">I could be shown, or I could be hidden</p>

The paragraph will be displayed when foo.bar is true, hidden when false.

Maven build debug in Eclipse

if you are using Maven 2.0.8+, then it will be very simple, run mvndebug from the console, and connect to it via Remote Debug Java Application with port 8000.

how to pass value from one php page to another using session

Use something like this:

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

Any other PHP page:

<?php
session_start();
echo $_SESSION['myValue'];
?>

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}

MySQL pivot table query with dynamic columns

I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.

SET @sql = '';
SELECT
    @sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
    SELECT
      DISTINCT
        CONCAT(
         'MAX(IF(pa.fieldname = ''',
          fieldname,
          ''', pa.fieldvalue, NULL)) AS ',
          fieldname
        ) as output
    FROM
        product_additional
) as temp;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

How to add column if not exists on PostgreSQL?

Following select query will return true/false, using EXISTS() function.

EXISTS():
The argument of EXISTS is an arbitrary SELECT statement, or subquery. The subquery is evaluated to determine whether it returns any rows. If it returns at least one row, the result of EXISTS is "true"; if the subquery returns no rows, the result of EXISTS is "false"

SELECT EXISTS(SELECT  column_name 
                FROM  information_schema.columns 
               WHERE  table_schema = 'public' 
                 AND  table_name = 'x' 
                 AND  column_name = 'y'); 

and use the following dynamic SQL statement to alter your table

DO
$$
BEGIN
IF NOT EXISTS (SELECT column_name 
                 FROM  information_schema.columns 
                WHERE  table_schema = 'public' 
                  AND  table_name = 'x' 
                  AND  column_name = 'y') THEN
ALTER TABLE x ADD COLUMN y int DEFAULT NULL;
ELSE
RAISE NOTICE 'Already exists';
END IF;
END
$$

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

Android : How to set onClick event for Button in List item of ListView

I find

final Button yourButton = (Button)view.findViewById(R.id.your_button);
yourButton.setFocusable(false);
yourButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        ...///);

can solve the problem. If you want to get some data when clicking the button, using tags is helpful. Here the button is declared final because it will be used within inner class.

Check if string matches pattern

import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.search(string)

How to get a string between two characters?

String s = "test string (67)";

int start = 0; // '(' position in string
int end = 0; // ')' position in string
for(int i = 0; i < s.length(); i++) { 
    if(s.charAt(i) == '(') // Looking for '(' position in string
       start = i;
    else if(s.charAt(i) == ')') // Looking for ')' position in  string
       end = i;
}
String number = s.substring(start+1, end); // you take value between start and end

Creating composite primary key in SQL Server

How about something like

CREATE TABLE testRequest (
        wardNo nchar(5),
        BHTNo nchar(5),
        testID nchar(5),
        reqDateTime datetime,
        PRIMARY KEY (wardNo, BHTNo, testID)
);

Have a look at this example

SQL Fiddle DEMO

NPM global install "cannot find module"

In my case both node and npm were in same path (/usr/bin). The NODE_PATH was empty, so the npm placed the global modules into /usr/lib/node_modules where require(...) successfully find them. The only exception was the npm module, which came with the nodejs package. Since I'm using 64 bit system, it was placed into /usr/lib64/node_modules. This is not where require(...) searches in case of empty NODE_PATH and node started from /usr/bin. So I had two options:

  • link /usr/lib64/node_modules/npm to /usr/lib/node_modules/npm
  • move modules from /usr/lib/node_modules/* to /usr/lib64/node_modules/ and set NODE_PATH=/usr/lib64/node_modules

Both worked. I'm using OpenSUSE 42.1 and the nodejs package from updates repository. Version is 4.4.5.

how to use math.pi in java

You're missing the multiplication operator. Also, you want to do 4/3 in floating point, not integer math.

volume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
           ^^      ^

How to highlight a current menu item?

I suggest using a directive on a link.

But its not perfect yet. Watch out for the hashbangs ;)

Here is the javascript for directive:

angular.module('link', []).
  directive('activeLink', ['$location', function (location) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs, controller) {
        var clazz = attrs.activeLink;
        var path = attrs.href;
        path = path.substring(1); //hack because path does not return including hashbang
        scope.location = location;
        scope.$watch('location.path()', function (newPath) {
          if (path === newPath) {
            element.addClass(clazz);
          } else {
            element.removeClass(clazz);
          }
        });
      }
    };
  }]);

and here is how it would be used in html:

<div ng-app="link">
  <a href="#/one" active-link="active">One</a>
  <a href="#/two" active-link="active">One</a>
  <a href="#" active-link="active">home</a>
</div>

afterwards styling with css:

.active { color: red; }

TypeError: p.easing[this.easing] is not a function

Including this worked for me.

Please include the line mentioned below in the section.

<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js'>

Align text in JLabel to the right

JLabel label = new JLabel("fax", SwingConstants.RIGHT);

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

How to change JDK version for an Eclipse project

See the page Set Up JDK in Eclipse. From the add button you can add a different version of the JDK...

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

If I understand your question correctly, I've made a fiddle that has this working correctly. This issue is with how you're assigning the event handlers and as others have said you have over riding event handlers. The current jQuery best practice is to use on() to register event handlers. Here's a link to the jQuery docs about on: link

Your original solution was pretty close but the way you added the event handlers is a bit confusing. It's considered best practice to not add events to HTML elements. I recommend reading up on Unobstrusive JavaScript.

Here's the JavaScript code. I added a counter variable so you can see that it is working correctly.

$('#answer').on('click', function() {
  feedback('hey there');
});

var counter = 0;

function feedback(message) {

  $('#feedback').remove();

  $('.answers').append('<div id="feedback">' + message + ' ' + counter + '</div>');

  counter++;    
}

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I had the same issue with firefox 38.

After using following version dependencies, I could resolve the issue.

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.0</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
        <version>2.53.0</version>
    </dependency> 

How to filter by string in JSONPath?

The browser testing tools while convenient can be a bit deceiving. Consider:

{
  "resourceType": "Encounter",
  "id": "EMR56788",
  "text": {
    "status": "generated",
    "div": "Patient admitted with chest pains</div>"
  },
  "status": "in-progress",
  "class": "inpatient",
  "patient": {
    "reference": "Patient/P12345",
    "display": "Roy Batty"
  }
}

Most tools returned this as false:

$[?(@.class==inpatient)]

But when I executed against

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>1.2.0</version>
</dependency>

It returned true. I recommend writing a simple unit test to verify rather than rely on the browser testing tools.

Controlling Spacing Between Table Cells

To get the job done, use

<table cellspacing=12>

If you’d rather “be right” than get things done, you can instead use the CSS property border-spacing, which is supported by some browsers.

Maven Unable to locate the Javac Compiler in:

In Eclipse, actions like importing Maven projects or invoking "Update Sources" runs in the same JVM in which Eclipse is running. If that JVM comes from JRE that isn’t part of JDK, there would be no Java compiler (the tools.jar).

So to launch Maven from within Eclipse, JRE used for launch also need to come from JDK. By default Eclipse registers JRE it is started in, but this can be configured on "Window / Preferences… / Java / Installed JREs" preference page as mentioned above by Parthasarathy

Alternatively you can specify compilerId in the pom.xml, so Maven won’t be looking for JDK when compiling Java code:

 <plugin>
  <artifactid>maven-compiler-plugin</artifactid>
  <configuration>
    <compilerid>eclipse</compilerid>
  </configuration>
  <dependencies>
    <dependency>
      <groupid>org.codehaus.plexus</groupid>
      <artifactid>plexus-compiler-eclipse</artifactid>
      <version>xxxx</version>
    </dependency>
  </dependencies>
</plugin>

How to remove unused imports in Intellij IDEA on commit?

Choose the project/module you want to remove unused import from in Project view. Then from Code menu choose Optimize imports and confirm with Run. The imports will be cleaned in whole project/module.

How to completely uninstall Visual Studio 2010?

There is a solution here : Add

/full /netfx at the end of the path!

This should clear almost all. You should only be left with SQL Server.

When is the @JsonProperty property used and what is it used for?

I think OldCurmudgeon and StaxMan are both correct but here is one sentence answer with simple example for you.

@JsonProperty(name), tells Jackson ObjectMapper to map the JSON property name to the annotated Java field's name.

//example of json that is submitted 
"Car":{
  "Type":"Ferrari",
}

//where it gets mapped 
public static class Car {
  @JsonProperty("Type")
  public String type;
 }

What is a user agent stylesheet?

Each browser provides a default stylesheet, called the user agent stylesheet, in case an HTML file does not specify one. Styles that you specify override the defaults.

Because you have not specified values for the table element’s box, the default styles have been applied.

How to add custom validation to an AngularJS form?

I recently created a directive to allow for expression-based invalidation of angular form inputs. Any valid angular expression can be used, and it supports custom validation keys using object notation. Tested with angular v1.3.8

        .directive('invalidIf', [function () {
        return {
            require: 'ngModel',
            link: function (scope, elm, attrs, ctrl) {

                var argsObject = scope.$eval(attrs.invalidIf);

                if (!angular.isObject(argsObject)) {
                    argsObject = { invalidIf: attrs.invalidIf };
                }

                for (var validationKey in argsObject) {
                    scope.$watch(argsObject[validationKey], function (newVal) {
                        ctrl.$setValidity(validationKey, !newVal);
                    });
                }
            }
        };
    }]);

You can use it like this:

<input ng-model="foo" invalid-if="{fooIsGreaterThanBar: 'foo > bar',
                                   fooEqualsSomeFuncResult: 'foo == someFuncResult()'}/>

Or by just passing in an expression (it will be given the default validationKey of "invalidIf")

<input ng-model="foo" invalid-if="foo > bar"/>

Select distinct values from a list using LINQ in C#

Try,

var newList = 
(
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}
).Distinct();

How to mock static methods in c# using MOQ framework?

Moq cannot mock a static member of a class.

When designing code for testability it's important to avoid static members (and singletons). A design pattern that can help you refactoring your code for testability is Dependency Injection.

This means changing this:

public class Foo
{
    public Foo()
    {
        Bar = new Bar();
    }
}

to

public Foo(IBar bar)
{
    Bar = bar;
}

This allows you to use a mock from your unit tests. In production you use a Dependency Injection tool like Ninject or Unity wich can wire everything together.

I wrote a blog about this some time ago. It explains which patterns an be used for better testable code. Maybe it can help you: Unit Testing, hell or heaven?

Another solution could be to use the Microsoft Fakes Framework. This is not a replacement for writing good designed testable code but it can help you out. The Fakes framework allows you to mock static members and replace them at runtime with your own custom behavior.

Create empty file using python

Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt"). The only drawback is that this call requires root privileges on OSX.

Why does AngularJS include an empty option in select?

We can use CSS to hide the first option , But it wont work in IE 10, 11. The best way is to remove the element using Jquery. This solution works for major browser tested in chrome and IE10 ,11

Also if you are using angular , sometime using setTimeout works

$scope.RemoveFirstOptionElement = function (element) {
    setTimeout(function () {
        $(element.children()[0]).remove();
    }, 0);
};

How to make g++ search for header files in a specific directory?

Headers included with #include <> will be searched in all default directories , but you can also add your own location in the search path with -I command line arg.

I saw your edit you could install your headers in default locations usually

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

Confirm with compiler docs though.

Rendering HTML elements to <canvas>

Take a look on MDN

It will render html element using creating SVG images.

For Example: There is <em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span> HTML element. And I want to add it into <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas> Canvas Element.

Here is Javascript Code to add HTML element to canvas.

_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
_x000D_
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +_x000D_
  '<foreignObject width="100%" height="100%">' +_x000D_
  '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +_x000D_
  '<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +_x000D_
  '</div>' +_x000D_
  '</foreignObject>' +_x000D_
  '</svg>';_x000D_
_x000D_
var DOMURL = window.URL || window.webkitURL || window;_x000D_
_x000D_
var img = new Image();_x000D_
var svg = new Blob([data], {_x000D_
  type: 'image/svg+xml;charset=utf-8'_x000D_
});_x000D_
var url = DOMURL.createObjectURL(svg);_x000D_
_x000D_
img.onload = function() {_x000D_
  ctx.drawImage(img, 0, 0);_x000D_
  DOMURL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
img.src = url;
_x000D_
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
_x000D_
_x000D_
_x000D_

How to give a pattern for new line in grep?

grep patterns are matched against individual lines so there is no way for a pattern to match a newline found in the input.

However you can find empty lines like this:

grep '^$' file
grep '^[[:space:]]*$' file # include white spaces 

MySQL Delete all rows from table and reset ID to zero

if you want to use truncate use this:

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table $table_name; 
SET FOREIGN_KEY_CHECKS = 1;

CASE .. WHEN expression in Oracle SQL

You could use an IN clause

Something like

SELECT
  status,
  CASE
    WHEN STATUS IN('a1','a2','a3')
    THEN 'Active'
    WHEN STATUS = 'i'
    THEN 'Inactive'
    WHEN STATUS = 't'
    THEN 'Terminated'
  END AS STATUSTEXT
FROM
  STATUS

Have a look at this demo

SQL Fiddle DEMO

Rename a table in MySQL

For Mysql 5.6.18 use the following command

ALTER TABLE `old_table` RENAME TO `new_table`

Also if there is an error saying ".... near RENAME TO ..." try removing the tick `

Git says local branch is behind remote branch, but it's not

You probably did some history rewriting? Your local branch diverged from the one on the server. Run this command to get a better understanding of what happened:

gitk HEAD @{u}

I would strongly recommend you try to understand where this error is coming from. To fix it, simply run:

git push -f

The -f makes this a “forced push” and overwrites the branch on the server. That is very dangerous when you are working in team. But since you are on your own and sure that your local state is correct this should be fine. You risk losing commit history if that is not the case.

How to Scroll Down - JQuery

This can be used in to solve this problem

<div id='scrol'></div> 

in javascript use this

jQuery("div#scrol").scrollTop(jQuery("div#scrol")[0].scrollHeight);

How do you build a Singleton in Dart?

Here's a concise example that combines the other solutions. Accessing the singleton can be done by:

  • Using a singleton global variable that points to the instance.
  • The common Singleton.instance pattern.
  • Using the default constructor, which is a factory that returns the instance.

Note: You should implement only one of the three options so that code using the singleton is consistent.

Singleton get singleton => Singleton.instance;
ComplexSingleton get complexSingleton => ComplexSingleton._instance;

class Singleton {
  static final Singleton instance = Singleton._private();
  Singleton._private();
  factory Singleton() => instance;
}

class ComplexSingleton {
  static ComplexSingleton _instance;
  static ComplexSingleton get instance => _instance;
  static void init(arg) => _instance ??= ComplexSingleton._init(arg);

  final property;
  ComplexSingleton._init(this.property);
  factory ComplexSingleton() => _instance;
}

If you need to do complex initialization, you'll just have to do so before using the instance later in the program.

Example

void main() {
  print(identical(singleton, Singleton.instance));        // true
  print(identical(singleton, Singleton()));               // true
  print(complexSingleton == null);                        // true
  ComplexSingleton.init(0); 
  print(complexSingleton == null);                        // false
  print(identical(complexSingleton, ComplexSingleton())); // true
}

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

In the old days, "/opt" was used by UNIX vendors like AT&T, Sun, DEC and 3rd-party vendors to hold "Option" packages; i.e. packages that you might have paid extra money for. I don't recall seeing "/opt" on Berkeley BSD UNIX. They used "/usr/local" for stuff that you installed yourself.

But of course, the true "meaning" of the different directories has always been somewhat vague. That is arguably a good thing, because if these directories had precise (and rigidly enforced) meanings you'd end up with a proliferation of different directory names.

According to the Filesystem Hierarchy Standard, /opt is for "the installation of add-on application software packages". /usr/local is "for use by the system administrator when installing software locally".

What is "android:allowBackup"?

It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"), it is possible to modify/read the content of an app even on a non-rooted device.

Solution - use android:allowBackup="false" in the manifest file.

You can read this post to have more information: Hacking Android Apps Using Backup Techniques

Passing parameter to controller from route in laravel

You can add them like this

  Route::get('company/{name}', 'PublicareaController@companydetails');

Where is virtualenvwrapper.sh after pip install?

Have you installed it using sudo? Was the error in my case.

How do I shut down a python simpleHTTPserver?

You are simply sending signals to the processes. kill is a command to send those signals.

The keyboard command Ctrl+C sends a SIGINT, kill -9 sends a SIGKILL, and kill -15 sends a SIGTERM.

What signal do you want to send to your server to end it?

Android ImageView setImageResource in code

you use that code

ImageView[] ivCard = new ImageView[1];

@override    
protected void onCreate(Bundle savedInstanceState)  

ivCard[0]=(ImageView)findViewById(R.id.imageView1);

Calling a class function inside of __init__

In parse_file, take the self argument (just like in __init__). If there's any other context you need then just pass it as additional arguments as usual.

How can I set a custom baud rate on Linux?

You can just use the normal termios header and normal termios structure (it's the same as the termios2 when using header asm/termios).

So, you open the device using open() and get a file descriptor, then use it in tcgetattr() to fill your termios structure.

Then clear CBAUD and set CBAUDEX on c_cflag. CBAUDEX has the same value as BOTHER.

After setting this, you can set a custom baud rate using normal functions, like cfsetspeed(), specifying the desired baud rate as an integer.

Should I use scipy.pi, numpy.pi, or math.pi?

>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True

So it doesn't matter, they are all the same value.

The only reason all three modules provide a pi value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.

How to set python variables to true or false?

you have to use capital True and False not true and false

how to add the missing RANDR extension

I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.

It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR warning and problem at starting Firefox using Xfvb.

After adding +extension RANDR it worked again.

$ vim /etc/init/xvfb.conf

#!upstart
description "Xvfb Server as a daemon"

start on filesystem and started networking
stop on shutdown

respawn

env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid

exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1

Regular expression for floating point numbers

TL;DR

Use [.] instead of \. and [0-9] instead of \d to avoid escaping issues in some languages (like Java).

Thanks to the nameless one for originally recognizing this.

One relatively simple pattern for matching a floating point number is

[+-]?([0-9]*[.])?[0-9]+

This will match:

  • 123
  • 123.456
  • .456

See a working example

If you also want to match 123. (a period with no decimal part), then you'll need a slightly longer expression:

[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)

See pkeller's answer for a fuller explanation of this pattern

If you want to include non-decimal numbers, such as hex and octal, see my answer to How do I identify if a string is a number?.

If you want to validate that an input is a number (rather than finding a number within the input), then you should surround the pattern with ^ and $, like so:

^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$

Irregular Regular Expressions

"Regular expressions", as implemented in most modern languages, APIs, frameworks, libraries, etc., are based on a concept developed in formal language theory. However, software engineers have added many extensions that take these implementations far beyond the formal definition. So, while most regular expression engines resemble one another, there is actually no standard. For this reason, a lot depends on what language, API, framework or library you are using.

(Incidentally, to help reduce confusion, many have taken to using "regex" or "regexp" to describe these enhanced matching languages. See Is a Regex the Same as a Regular Expression? at RexEgg.com for more information.)

That said, most regex engines (actually, all of them, as far as I know) would accept \.. Most likely, there's an issue with escaping.

The Trouble with Escaping

Some languages have built-in support for regexes, such as JavaScript. For those languages that don't, escaping can be a problem.

This is because you are basically coding in a language within a language. Java, for example, uses \ as an escape character within it's strings, so if you want to place a literal backslash character within a string, you must escape it:

// creates a single character string: "\"
String x = "\\";

However, regexes also use the \ character for escaping, so if you want to match a literal \ character, you must escape it for the regexe engine, and then escape it again for Java:

// Creates a two-character string: "\\"
// When used as a regex pattern, will match a single character: "\"
String regexPattern = "\\\\";

In your case, you have probably not escaped the backslash character in the language you are programming in:

// will most likely result in an "Illegal escape character" error
String wrongPattern = "\.";
// will result in the string "\."
String correctPattern = "\\.";

All this escaping can get very confusing. If the language you are working with supports raw strings, then you should use those to cut down on the number of backslashes, but not all languages do (most notably: Java). Fortunately, there's an alternative that will work some of the time:

String correctPattern = "[.]";

For a regex engine, \. and [.] mean exactly the same thing. Note that this doesn't work in every case, like newline (\\n), open square bracket (\\[) and backslash (\\\\ or [\\]).

A Note about Matching Numbers

(Hint: It's harder than you think)

Matching a number is one of those things you'd think is quite easy with regex, but it's actually pretty tricky. Let's take a look at your approach, piece by piece:

[-+]?

Match an optional - or +

[0-9]*

Match 0 or more sequential digits

\.?

Match an optional .

[0-9]*

Match 0 or more sequential digits

First, we can clean up this expression a bit by using a character class shorthand for the digits (note that this is also susceptible to the escaping issue mentioned above):

[0-9] = \d

I'm going to use \d below, but keep in mind that it means the same thing as [0-9]. (Well, actually, in some engines \d will match digits from all scripts, so it'll match more than [0-9] will, but that's probably not significant in your case.)

Now, if you look at this carefully, you'll realize that every single part of your pattern is optional. This pattern can match a 0-length string; a string composed only of + or -; or, a string composed only of a .. This is probably not what you've intended.

To fix this, it's helpful to start by "anchoring" your regex with the bare-minimum required string, probably a single digit:

\d+

Now we want to add the decimal part, but it doesn't go where you think it might:

\d+\.?\d* /* This isn't quite correct. */

This will still match values like 123.. Worse, it's got a tinge of evil about it. The period is optional, meaning that you've got two repeated classes side-by-side (\d+ and \d*). This can actually be dangerous if used in just the wrong way, opening your system up to DoS attacks.

To fix this, rather than treating the period as optional, we need to treat it as required (to separate the repeated character classes) and instead make the entire decimal portion optional:

\d+(\.\d+)? /* Better. But... */

This is looking better now. We require a period between the first sequence of digits and the second, but there's a fatal flaw: we can't match .123 because a leading digit is now required.

This is actually pretty easy to fix. Instead of making the "decimal" portion of the number optional, we need to look at it as a sequence of characters: 1 or more numbers that may be prefixed by a . that may be prefixed by 0 or more numbers:

(\d*\.)?\d+

Now we just add the sign:

[+-]?(\d*\.)?\d+

Of course, those slashes are pretty annoying in Java, so we can substitute in our long-form character classes:

[+-]?([0-9]*[.])?[0-9]+

Matching versus Validating

This has come up in the comments a couple times, so I'm adding an addendum on matching versus validating.

The goal of matching is to find some content within the input (the "needle in a haystack"). The goal of validating is to ensure that the input is in an expected format.

Regexes, by their nature, only match text. Given some input, they will either find some matching text or they will not. However, by "snapping" an expression to the beginning and ending of the input with anchor tags (^ and $), we can ensure that no match is found unless the entire input matches the expression, effectively using regexes to validate.

The regex described above ([+-]?([0-9]*[.])?[0-9]+) will match one or more numbers within a target string. So given the input:

apple 1.34 pear 7.98 version 1.2.3.4

The regex will match 1.34, 7.98, 1.2, .3 and .4.

To validate that a given input is a number and nothing but a number, "snap" the expression to the start and end of the input by wrapping it in anchor tags:

^[+-]?([0-9]*[.])?[0-9]+$

This will only find a match if the entire input is a floating point number, and will not find a match if the input contains additional characters. So, given the input 1.2, a match will be found, but given apple 1.2 pear no matches will be found.

Note that some regex engines have a validate, isMatch or similar function, which essentially does what I've described automatically, returning true if a match is found and false if no match is found. Also keep in mind that some engines allow you to set flags which change the definition of ^ and $, matching the beginning/end of a line rather than the beginning/end of the entire input. This is typically not the default, but be on the lookout for these flags.

Check if value exists in column in VBA

If you want to do this without VBA, you can use a combination of IF, ISERROR, and MATCH.

So if all values are in column A, enter this formula in column B:

=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0))

This will look for the value "12345" (which can also be a cell reference). If the value isn't found, MATCH returns "#N/A" and ISERROR tries to catch that.

If you want to use VBA, the quickest way is to use a FOR loop:

Sub FindMatchingValue()
    Dim i as Integer, intValueToFind as integer
    intValueToFind = 12345
    For i = 1 to 500    ' Revise the 500 to include all of your values
        If Cells(i,1).Value = intValueToFind then 
            MsgBox("Found value on row " & i)
            Exit Sub
        End If
    Next i

    ' This MsgBox will only show if the loop completes with no success
    MsgBox("Value not found in the range!")  
End Sub

You can use Worksheet Functions in VBA, but they're picky and sometimes throw nonsensical errors. The FOR loop is pretty foolproof.

How to add new DataRow into DataTable?

    GRV.DataSource = Class1.DataTable;
            GRV.DataBind();

Class1.GRV.Rows[e.RowIndex].Delete();
        GRV.DataSource = Class1.DataTable;
        GRV.DataBind();

List submodules in a Git repository

I use this one:

git submodule status | cut -d' ' -f3-4 

Output (path + version):

tools/deploy_utils (0.2.4)

adding css class to multiple elements

try this:

.button input, .button a {
//css here
}

That will apply the style to all a tags nested inside of <p class="button"></p>

SQL NVARCHAR and VARCHAR Limits

You mus use nvarchar text too. that's mean you have to simply had a "N" before your massive string and that's it! no limitation anymore

DELARE @SQL NVARCHAR(MAX);
SET @SQL = N'SomeMassiveString > 4000 chars...';
EXEC(@SQL);
GO

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.

java.lang.IllegalArgumentException: No enum constant

Also the problem was when we at Parcelize read moment write some short if.

My solution for this was

1.Create companion object with parsing method.

enum class CarsType {
    @Json(name = "SMALL")
    SMALL,
    @Json(name = "BIG")
    BIG;

    companion object {
        fun nullableValueOf(name: String?) = when (name) {
            null -> null
            else -> valueOf(name)
        }
    }
}

2. In Parcerable read place use it like this

data class CarData(
    val carId: String? = null,
    val carType: CarsType?,
    val data: String?
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        CarsType.nullableValueOf(parcel.readString()),
        parcel.readString())

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

Isn't this maybe the most elegant?

REPLACE 
INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) 
VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')

see: http://dev.mysql.com/doc/refman/5.7/en/replace.html

Get the list of stored procedures created and / or modified on a particular date?

SELECT name
FROM sys.objects
WHERE type = 'P'
AND (DATEDIFF(D,modify_date, GETDATE()) < 7
     OR DATEDIFF(D,create_date, GETDATE()) < 7)

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

The most likely explanations for that error are:

  1. The file you are attempting to load is not an executable file. CreateProcess requires you to provide an executable file. If you wish to be able to open any file with its associated application then you need ShellExecute rather than CreateProcess.
  2. There is a problem loading one of the dependencies of the executable, i.e. the DLLs that are linked to the executable. The most common reason for that is a mismatch between a 32 bit executable and a 64 bit DLL, or vice versa. To investigate, use Dependency Walker's profile mode to check exactly what is going wrong.

Reading down to the bottom of the code, I can see that the problem is number 1.

How to calculate moving average without keeping the count and data-total?

You can simply do:

double approxRollingAverage (double avg, double new_sample) {

    avg -= avg / N;
    avg += new_sample / N;

    return avg;
}

Where N is the number of samples where you want to average over. Note that this approximation is equivalent to an exponential moving average. See: Calculate rolling / moving average in C++

How can I update my ADT in Eclipse?

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help

  2. Install New Software ---> Add

  3. inside Add Repository write the Name: ADT (or whatever you want)

  4. Location: https://dl-ssl.google.com/android/eclipse/

  5. after loading you should get Developer Tools and NDK Plugins

  6. check both if you want to use the Native Developer Kit (NDK) in the future or check

  7. Developer Tool only

  8. click Next

  9. Finish

How can I Insert data into SQL Server using VBNet

It means that the number of values specified in your VALUES clause on the INSERT statement is not equal to the total number of columns in the table. You must specify the columnname if you only try to insert on selected columns.

Another one, since you are using ADO.Net , always parameterized your query to avoid SQL Injection. What you are doing right now is you are defeating the use of sqlCommand.

ex

Dim query as String = String.Empty
query &= "INSERT INTO student (colName, colID, colPhone, "
query &= "                     colBranch, colCourse, coldblFee)  "
query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse, @coldblFee)"

Using conn as New SqlConnection("connectionStringHere")
    Using comm As New SqlCommand()
        With comm
            .Connection = conn
            .CommandType = CommandType.Text
            .CommandText = query
            .Parameters.AddWithValue("@colName", strName)
            .Parameters.AddWithValue("@colID", strId)
            .Parameters.AddWithValue("@colPhone", strPhone)
            .Parameters.AddWithValue("@colBranch", strBranch)
            .Parameters.AddWithValue("@colCourse", strCourse)
            .Parameters.AddWithValue("@coldblFee", dblFee)
        End With
        Try
            conn.open()
            comm.ExecuteNonQuery()
        Catch(ex as SqlException)
            MessageBox.Show(ex.Message.ToString(), "Error Message")
        End Try
    End Using
End USing 

PS: Please change the column names specified in the query to the original column found in your table.

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

In MVC5.2, add Date.cshtml to folder ~/Views/Shared/EditorTemplates:

@model DateTime?
@{
    IDictionary<string, object> htmlAttributes;
    object objAttributes;
    if (ViewData.TryGetValue("htmlAttributes", out objAttributes))
    {
        htmlAttributes = objAttributes as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(objAttributes);
    }
    else
    {
        htmlAttributes = new RouteValueDictionary();
    }
    htmlAttributes.Add("type", "date");
    String format = (Request.UserAgent != null && Request.UserAgent.Contains("Chrome")) ? "{0:yyyy-MM-dd}" : "{0:d}";
    @Html.TextBox("", Model, format, htmlAttributes)
}

Making div content responsive

try this css:

/* Show in default resolution screen*/
#container2 {
width: 960px;
position: relative;
margin:0 auto;
line-height: 1.4em;
}

/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */    
@media only screen and (max-width: 479px){
    #container2 { width: 90%; }
}

Here the demo: http://jsfiddle.net/ongisnade/CG9WN/

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

Allow click on twitter bootstrap dropdown toggle link?

I'm not sure about the issue for making the top level anchor element a clickable anchor but here's the simplest solution for making desktop views have the hover effect, and mobile views maintaining their click-ability.

// Medium screens and up only
@media only screen and (min-width: $screen-md-min) {
    // Enable menu hover for bootstrap
    // dropdown menus
    .dropdown:hover .dropdown-menu {
        display: block;
    }
}

This way the mobile menu still behaves as it should, while the desktop menu will expand on hover instead of on a click.

How to do a SUM() inside a case statement in SQL server

If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ().

case 
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore

But it'll be better if you show your full query to get context of what you actually need.

SQL Developer is returning only the date, not the time. How do I fix this?

Date format can also be set by using below query :-

alter SESSION set NLS_DATE_FORMAT = 'date_format'

e.g. : alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS'

How to show and update echo on same line

I use printf, is shorter as it doesn't need flags to do the work:

printf "\rMy static $myvars composed text"

Creating a List of Lists in C#

or this example, just to make it more visible:

public class CustomerListList : List<CustomerList> { }  

public class CustomerList : List<Customer> { }

public class Customer
{
   public int ID { get; set; }
   public string SomethingWithText { get; set; }
}

and you can keep it going. to the infinity and beyond !

format statement in a string resource file

You should add formatted="false" to your string resource


Here is an example

In your strings.xml :

<string name="all" formatted="false">Amount: %.2f%n  for %d days</string>

In your code:

yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));

jQuery.click() vs onClick

<whatever onclick="doStuff();" onmouseover="in()" onmouseout="out()" />

onclick, onmouseover, onmouseout, etc. events are actually bad for performance (in Internet Explorer mainly, go figure). If you code using Visual Studio, when you run a page with these, every single one of these will create a separate SCRIPT block taking up memory, and thus slowing down performance.

Not to mention you should have a separation of concerns: JavaScript and layouts should be separated!

It is always better to create evenHandlers for any of these events, one event can capture hundreds/thousands of items, instead of creating thousands of separate script blocks for each one!

(Also, everything everyone else is saying.)

Mailto on submit button

What you need to do is use the onchange event listener in the form and change the href attribute of the send button according to the context of the mail:

<form id="form" onchange="mail(this)">
  <label>Name</label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="name" type="text">
    </div>
  </div>

  <label>Email <span class="color-red">*</span></label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="email" type="text">
    </div>
  </div>

  <label>Date of visit/departure </label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control w8em" name="adate" type="text">
      <script>
        datePickerController.createDatePicker({
          // Associate the text input to a DD/MM/YYYY date format
          formElements: {
            "adate": "%d/%m/%Y"
          }
        });
      </script>
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" name="ddate" type="date">
    </div>
  </div>

  <label>No. of people travelling with</label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Adults" min=1 name="adult" type="number">
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Children" min=0 name="childeren" type="number">
    </div>
  </div>

  <label>Cities you want to visit</label><br />
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Cassablanca">Cassablanca</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Fez">Fez</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Tangier">Tangier</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Marrakech">Marrakech</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Rabat">Rabat</label>
  </div>

  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="4" placeholder="Activities Intersted in" name="activities" class="form-control"></textarea>
    </div>
  </div>


  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="6" class="form-control" name="comment" placeholder="Comment"></textarea>
    </div>
  </div>

  <p><a id="send" class="btn btn-primary">Create Message</a></p>
</form>

JavaScript

function mail(form) {
    var name = form.name.value;
    var city = "";
    var adate = form.adate.value;
    var ddate = form.ddate.value;
    var activities = form.activities.value;
    var adult = form.adult.value;
    var child = form.childeren.value;
    var comment = form.comment.value;
    var warning = ""
    for (i = 0; i < form.city.length; i++) {
        if (form.city[i].checked)
            city += " " + form.city[i].value;
    }
    var str = "mailto:[email protected]?subject=travel to morocco&body=";
    if (name.length > 0) {
        str += "Hi my name is " + name + ", ";
    } else {
        warning += "Name is required"
    }
    if (city.length > 0) {
        str += "I am Intersted in visiting the following citis: " + city + ", ";
    }
    if (activities.length > 0) {
        str += "I am Intersted in following activities: " + activities + ". "
    }
    if (adate.length > 0) {
        str += "I will be ariving on " + adate;
    }
    if (ddate.length > 0) {
        str += " And departing on " + ddate;
    }
    if (adult.length > 0) {
        if (adult == 1 && child == null) {
            str += ". I will be travelling alone"
        } else if (adult > 1) {
            str += ".We will have a group of " + adult + " adults ";
        }
        if (child == null) {
            str += ".";
        } else if (child > 1) {
            str += "along with " + child + " children.";
        } else if (child == 1) {
            str += "along with a child.";
        }
    }

    if (comment.length > 0) {
        str += "%0D%0A" + comment + "."
    }

    if (warning.length > 0) {
        alert(warning)
    } else {
        str += "%0D%0ARegards,%0D%0A" + name;
        document.getElementById('send').href = str;
    }
}

Read a text file in R line by line

I write a code to read file line by line to meet my demand which different line have different data type follow articles: read-line-by-line-of-a-file-in-r and determining-number-of-linesrecords. And it should be a better solution for big file, I think. My R version (3.3.2).

con = file("pathtotargetfile", "r")
readsizeof<-2    # read size for one step to caculate number of lines in file
nooflines<-0     # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0)    # calculate number of lines. Also a better solution for big file
  nooflines<-nooflines+linesread

con = file("pathtotargetfile", "r")    # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0)    # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
  tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
  print(is.vector(tmp))
  print(tmp)
}
close(con)

Rollback transaction after @Test

Aside: attempt to amend Tomasz Nurkiewicz's answer was rejected:

This edit does not make the post even a little bit easier to read, easier to find, more accurate or more accessible. Changes are either completely superfluous or actively harm readability.


Correct and permanent link to the relevant section of documentation about integration testing.

To enable support for transactions, you must configure a PlatformTransactionManager bean in the ApplicationContext that is loaded via @ContextConfiguration semantics.

@Configuration
@PropertySource("application.properties")
public class Persistence {
    @Autowired
    Environment env;

    @Bean
    DataSource dataSource() {
        return new DriverManagerDataSource(
                env.getProperty("datasource.url"),
                env.getProperty("datasource.user"),
                env.getProperty("datasource.password")
        );
    }

    @Bean
    PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}

In addition, you must declare Spring’s @Transactional annotation either at the class or method level for your tests.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Persistence.class, SomeRepository.class})
@Transactional
public class SomeRepositoryTest { ... }

Annotating a test method with @Transactional causes the test to be run within a transaction that will, by default, be automatically rolled back after completion of the test. If a test class is annotated with @Transactional, each test method within that class hierarchy will be run within a transaction.

How to detect chrome and safari browser (webkit)

There is still quirks and inconsistencies in 2019.

For example with scaled svg and pointer events, between browsers.

None of the answer of this topic are working anymore. (maybe those with jquery)

Here is an alternative, by testing with javascript if a css rule is supported, via the native CSS support api. Might evolve, to be adapted!

Note that it's possible to pass many css rules separated by a semicolon, for the finest detection.

_x000D_
_x000D_
if (CSS.supports("( -webkit-box-reflect:unset )")){
  console.log("WEBKIT BROWSER")
  // More math...
 } else {
  console.log("ENJOY")
 }
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
if (CSS.supports("( -moz-user-select:unset )")){
  console.log("FIREFOX!!!")
 }
_x000D_
_x000D_
_x000D_

Beware to not use it in loops, for performance it's better to populate a constant on load:

const ff = CSS.supports("( -moz-user-select:unset )")
if (ff){ //... } 

Using CSS only, the above would be:

_x000D_
_x000D_
@supports (-webkit-box-reflect:unset) {
  div {
    background: red
  }
}

@supports (-moz-user-select:unset) {
  div {
    background: green
  }
}
_x000D_
<div>
  Hello world!!
</div>
_x000D_
_x000D_
_x000D_

List of possible -webkit- only css rules.

List of possible -moz- only rules.

Can I use css support?