Programs & Examples On #Camino

Camino is an OSX browser which uses the Gecko engine and follows the Apple style and user interface guidelines, unlike its sibling, the Firefox browser.

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();
});

How do I UPDATE from a SELECT in SQL Server?

Consolidating all the different approaches here.

  1. Select update
  2. Update with a common table expression
  3. Merge

Sample table structure is below and will update from Product_BAK to Product table.

Product

CREATE TABLE [dbo].[Product](
    [Id] [int] IDENTITY(1, 1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
    [Description] [nvarchar](100) NULL
) ON [PRIMARY]

Product_BAK

    CREATE TABLE [dbo].[Product_BAK](
        [Id] [int] IDENTITY(1, 1) NOT NULL,
        [Name] [nvarchar](100) NOT NULL,
        [Description] [nvarchar](100) NULL
    ) ON [PRIMARY]

1. Select update

    update P1
    set Name = P2.Name
    from Product P1
    inner join Product_Bak P2 on p1.id = P2.id
    where p1.id = 2

2. Update with a common table expression

    ; With CTE as
    (
        select id, name from Product_Bak where id = 2
    )
    update P
    set Name = P2.name
    from  product P  inner join CTE P2 on P.id = P2.id
    where P2.id = 2

3. Merge

    Merge into product P1
    using Product_Bak P2 on P1.id = P2.id

    when matched then
    update set p1.[description] = p2.[description], p1.name = P2.Name;

In this Merge statement, we can do inset if not finding a matching record in the target, but exist in the source and please find syntax:

    Merge into product P1
    using Product_Bak P2 on P1.id = P2.id;

    when matched then
    update set p1.[description] = p2.[description], p1.name = P2.Name;

    WHEN NOT MATCHED THEN
    insert (name, description)
    values(p2.name, P2.description);

Can we have multiple "WITH AS" in single sql - Oracle SQL

Yes you can...

WITH SET1 AS (SELECT SYSDATE FROM DUAL), -- SET1 initialised
     SET2 AS (SELECT * FROM SET1)        -- SET1 accessed
SELECT * FROM SET2;                      -- SET2 projected

10/29/2013 10:43:26 AM

Follow the order in which it should be initialized in Common Table Expressions

Restrict SQL Server Login access to only one database

  1. Connect to your SQL server instance using management studio
  2. Goto Security -> Logins -> (RIGHT CLICK) New Login
  3. fill in user details
  4. Under User Mapping, select the databases you want the user to be able to access and configure

UPDATE:

You'll also want to goto Security -> Server Roles, and for public check the permissions for TSQL Default TCP/TSQL Default VIA/TSQL Local Machine/TSQL Named Pipesand remove the connect permission

2D character array initialization in C

char **options[2][100];

declares a size-2 array of size-100 arrays of pointers to pointers to char. You'll want to remove one *. You'll also want to put your string literals in double quotes.

iOS Detection of Screenshot?

Latest SWIFT 3:

func detectScreenShot(action: @escaping () -> ()) {
        let mainQueue = OperationQueue.main
        NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot, object: nil, queue: mainQueue) { notification in
            // executes after screenshot
            action()
        }
    }

In viewDidLoad, call this function

detectScreenShot { () -> () in
 print("User took a screen shot")
}

However,

NotificationCenter.default.addObserver(self, selector: #selector(test), name: .UIApplicationUserDidTakeScreenshot, object: nil)

    func test() {
    //do stuff here
    }

works totally fine. I don't see any points of mainQueue...

Checking if jquery is loaded using Javascript

if ('undefined' == typeof window.jQuery) {
    // jQuery not present
} else {
    // jQuery present
}

How to secure an ASP.NET Web API

Update:

I have added this link to my other answer how to use JWT authentication for ASP.NET Web API here for anyone interested in JWT.


We have managed to apply HMAC authentication to secure Web API, and it worked okay. HMAC authentication uses a secret key for each consumer which both consumer and server both know to hmac hash a message, HMAC256 should be used. Most of the cases, hashed password of the consumer is used as a secret key.

The message normally is built from data in the HTTP request, or even customized data which is added to HTTP header, the message might include:

  1. Timestamp: time that request is sent (UTC or GMT)
  2. HTTP verb: GET, POST, PUT, DELETE.
  3. post data and query string,
  4. URL

Under the hood, HMAC authentication would be:

Consumer sends a HTTP request to web server, after building the signature (output of hmac hash), the template of HTTP request:

User-Agent: {agent}   
Host: {host}   
Timestamp: {timestamp}
Authentication: {username}:{signature}

Example for GET request:

GET /webapi.hmac/api/values

User-Agent: Fiddler    
Host: localhost    
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

The message to hash to get signature:

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n

Example for POST request with query string (signature below is not correct, just an example)

POST /webapi.hmac/api/values?key2=value2

User-Agent: Fiddler    
Host: localhost    
Content-Type: application/x-www-form-urlencoded
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

key1=value1&key3=value3

The message to hash to get signature

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n
key1=value1&key2=value2&key3=value3

Please note that form data and query string should be in order, so the code on the server get query string and form data to build the correct message.

When HTTP request comes to the server, an authentication action filter is implemented to parse the request to get information: HTTP verb, timestamp, uri, form data and query string, then based on these to build signature (use hmac hash) with the secret key (hashed password) on the server.

The secret key is got from the database with the username on the request.

Then server code compares the signature on the request with the signature built; if equal, authentication is passed, otherwise, it failed.

The code to build signature:

private static string ComputeHash(string hashedPassword, string message)
{
    var key = Encoding.UTF8.GetBytes(hashedPassword.ToUpper());
    string hashString;

    using (var hmac = new HMACSHA256(key))
    {
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
        hashString = Convert.ToBase64String(hash);
    }

    return hashString;
}

So, how to prevent replay attack?

Add constraint for the timestamp, something like:

servertime - X minutes|seconds  <= timestamp <= servertime + X minutes|seconds 

(servertime: time of request coming to server)

And, cache the signature of the request in memory (use MemoryCache, should keep in the limit of time). If the next request comes with the same signature with the previous request, it will be rejected.

The demo code is put as here: https://github.com/cuongle/Hmac.WebApi

Update TextView Every Second

Use TextSwitcher (for nice text transition animation) and timer instead.

Curl command line for consuming webServices?

Posting a string:

curl -d "String to post" "http://www.example.com/target"

Posting the contents of a file:

curl -d @soap.xml "http://www.example.com/target"

Convert line endings

Doing this with POSIX is tricky:

  • POSIX Sed does not support \r or \15. Even if it did, the in place option -i is not POSIX

  • POSIX Awk does support \r and \15, however the -i inplace option is not POSIX

  • d2u and dos2unix are not POSIX utilities, but ex is

  • POSIX ex does not support \r, \15, \n or \12

To remove carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file

To add carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file

How do you access a website running on localhost from iPhone browser

Local server machine: Linux

Accessing machine: iPad 13.5.1

I learned that the local server's host IP needs to be set to 0.0.0.0 for other machines to access it. To check, run sudo netstat -anp and look for your local server port. I found that it was running on 127.0.0.1 or localhost so other machines weren't able to access it. I changed my app configurations to run on host IP 0.0.0.0. I then used the <internetIP>:<port> to access the local server, and it worked

How do you decompile a swf file

Usually 'lost' is a euphemism for "We stopped paying the developer and now he wont give us the source code."

That being said, I own a copy of Burak's ActionScript Viewer, and it works pretty well. A simple google search will find you many other SWF decompilers.

Replace given value in vector

Why the fuss?

replace(haystack, haystack %in% needles, replacements)

Demo:

haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")

replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"

Pandas join issue: columns overlap but no suffix specified

Your error on the snippet of data you posted is a little cryptic, in that because there are no common values, the join operation fails because the values don't overlap it requires you to supply a suffix for the left and right hand side:

In [173]:

df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_right')
Out[173]:
       mukey_left  DI  PI  mukey_right  niccdcd
index                                          
0          100000  35  14          NaN      NaN
1         1000005  44  14          NaN      NaN
2         1000006  44  14          NaN      NaN
3         1000007  43  13          NaN      NaN
4         1000008  43  13          NaN      NaN

merge works because it doesn't have this restriction:

In [176]:

df_a.merge(df_b, on='mukey', how='left')
Out[176]:
     mukey  DI  PI  niccdcd
0   100000  35  14      NaN
1  1000005  44  14      NaN
2  1000006  44  14      NaN
3  1000007  43  13      NaN
4  1000008  43  13      NaN

jQuery Scroll To bottom of the page

something like this:

var $target = $('html,body'); 
$target.animate({scrollTop: $target.height()}, 1000);

Java: splitting a comma-separated string but ignoring commas in quotes

You're in that annoying boundary area where regexps almost won't do (as has been pointed out by Bart, escaping the quotes would make life hard) , and yet a full-blown parser seems like overkill.

If you are likely to need greater complexity any time soon I would go looking for a parser library. For example this one

How does one get started with procedural generation?

the most important thing is to analyze how roads, cities, blocks and buildings are structured. find out what all eg buildings have in common. look at photos, maps, plans and reality. if you do that you will be one step ahead of people who consider city building as a merely computer-technological matter.

next you should develop solutions on how to create that geometry in tiny, distinct steps. you have to define rules that make up a believable city. if you are into 3d modelling you have to rethink a lot of what you have learned so the computer can follow your instructions in any situation.

in order to not loose track you should set up a lot of operators that are only responsible for little parts of the whole process. that makes debugging, expanding and improving your system much easier. in the next step you should link those operators and check the results by changing parameters.

i have seen too many "city generators" that mainly consist of random-shaped boxes with some window textures on them : (

SQL Error: ORA-00913: too many values

this is a bit late.. but i have seen this problem occurs when you want to insert or delete one line from/to DB but u put/pull more than one line or more than one value ,

E.g:

you want to delete one line from DB with a specific value such as id of an item but you've queried a list of ids then you will encounter the same exception message.

regards.

Get full path of a file with FileUpload Control

FileUpload will never give you the full path for security reasons.

@RequestBody and @ResponseBody annotations in Spring

package com.programmingfree.springshop.controller;

import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.programmingfree.springshop.dao.UserShop;
import com.programmingfree.springshop.domain.User;


@RestController
@RequestMapping("/shop/user")
public class SpringShopController {

 UserShop userShop=new UserShop();

 @RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
 public User getUser(@PathVariable int id) {
  User user=userShop.getUserById(id);
  return user;
 }


 @RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
 public List<User> getAllUsers() {
  List<User> users=userShop.getAllUsers();
  return users;
 }


}

In the above example they going to display all user and particular id details now I want to use both id and name,

1) localhost:8093/plejson/shop/user <---this link will display all user details
2) localhost:8093/plejson/shop/user/11 <----if i use 11 in link means, it will display particular user 11 details

now I want to use both id and name

localhost:8093/plejson/shop/user/11/raju <-----------------like this it means we can use any one in this please help me out.....

How do I center text vertically and horizontally in Flutter?

Put the Text in a Center:

Container(
      height: 45,
      color: Colors.black,
      child: Center(
        child: Text(
            'test',
            style: TextStyle(color: Colors.white),
        ),
      ),
    );

Using WGET to run a cronjob PHP

I tried following format, working fine

*/5 * * * * wget --quiet -O /dev/null http://localhost/cron.php

How do we control web page caching, across all browsers?

Not sure if my answer sounds simple and stupid, and perhaps it has already been known to you since long time ago, but since preventing someone from using browser back button to view your historical pages is one of your goals, you can use:

window.location.replace("https://www.example.com/page-not-to-be-viewed-in-browser-history-back-button.html");

Of course, this may not be possible to be implemented across the entire site, but at least for some critical pages, you can do that. Hope this helps.

How can I use a batch file to write to a text file?

echo "blahblah"> txt.txt will erase the txt and put blahblah in it's place

echo "blahblah">> txt.txt will write blahblah on a new line in the txt

I think that both will create a new txt if none exists (I know that the first one does)

Where "txt.txt" is written above, a file path can be inserted if wanted. e.g. C:\Users\<username>\desktop, which will put it on their desktop.

Is there an online application that automatically draws tree structures for phrases/sentences?

There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.

The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.

Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

How to get json response using system.net.webrequest in c#?

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place

How to display 3 buttons on the same line in css

The following will display all 3 buttons on the same line provided there is enough horizontal space to display them:

<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
// Note the lack of unnecessary divs, floats, etc. 

The only reason the buttons wouldn't display inline is if they have had display:block applied to them within your css.

What are the differences between Abstract Factory and Factory design patterns?

I would favor Abstract Factory over Factory Method anytime. From Tom Dalling's example (great explanation btw) above, we can see that Abstract Factory is more composable in that all we need to do is passing a different Factory to the constructor (constructor dependency injection in use here). But Factory Method requires us to introduce a new class (more things to manage) and use subclassing. Always prefer composition over inheritance.

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

How to return multiple values?

You can return an object of a Class in Java.

If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.

If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

Arduino Tools > Serial Port greyed out

So I did with sudo usermod -a -G dialout <my-username>.

You need to log out after you add yourself to a group so those changes are applied. Just log out and log in again and the menu should be available.

hibernate could not get next sequence value

If using Postgres, create sequence manually with name 'hibernate_sequence'. It will work.

How to use a variable for a key in a JavaScript object literal?

I have used the following to add a property with a "dynamic" name to an object:

var key = 'top';
$('#myElement').animate(
   (function(o) { o[key]=10; return o;})({left: 20, width: 100}),
   10
);

key is the name of the new property.

The object of properties passed to animate will be {left: 20, width: 100, top: 10}

This is just using the required [] notation as recommended by the other answers, but with fewer lines of code!

Capturing a single image from my webcam in Java or Python

On windows it is easy to interact with your webcam with pygame:

from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')

I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux

Filter dataframe rows if value in column is in a set list of values

You can use query, i.e.:

b = df.query('a > 1 & a < 5')

can we use xpath with BeautifulSoup?

Maybe you can try the following without XPath

from simplified_scrapy.simplified_doc import SimplifiedDoc 
html = '''
<html>
<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
'''
# What XPath can do, so can it
doc = SimplifiedDoc(html)
# The result is the same as doc.getElementByTag('body').getElementByTag('div').getElementByTag('h1').text
print (doc.body.div.h1.text)
print (doc.div.h1.text)
print (doc.h1.text) # Shorter paths will be faster
print (doc.div.getChildren())
print (doc.div.getChildren('p'))

Trust Anchor not found for Android SSL Connection

I know that you don't need to trust all certificates but in my case I had problems with some debugging environments where we had self-signed certificates and I needed a dirty solution.

All I had to do was to change the initialization of the sslContext

mySSLContext.init(null, trustAllCerts, null); 

where trustAllCerts was created like this:

private final TrustManager[] trustAllCerts= new TrustManager[] { new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[]{};
    }

    public void checkClientTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
    }
} };

Hope that this will come in handy.

How do you execute an arbitrary native command from a string?

The accepted answer wasn't working for me when trying to parse the registry for uninstall strings, and execute them. Turns out I didn't need the call to Invoke-Expression after all.

I finally came across this nice template for seeing how to execute uninstall strings:

$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$app = 'MyApp'
$apps= @{}
Get-ChildItem $path | 
    Where-Object -FilterScript {$_.getvalue('DisplayName') -like $app} | 
    ForEach-Object -process {$apps.Set_Item(
        $_.getvalue('UninstallString'),
        $_.getvalue('DisplayName'))
    }

foreach ($uninstall_string in $apps.GetEnumerator()) {
    $uninstall_app, $uninstall_arg = $uninstall_string.name.split(' ')
    & $uninstall_app $uninstall_arg
}

This works for me, namely because $app is an in house application that I know will only have two arguments. For more complex uninstall strings you may want to use the join operator. Also, I just used a hash-map, but really, you'd probably want to use an array.

Also, if you do have multiple versions of the same application installed, this uninstaller will cycle through them all at once, which confuses MsiExec.exe, so there's that too.

How do I force files to open in the browser instead of downloading (PDF)?

You can do this in the following way:

<a href="path to PDF file">Open PDF</a>

If the PDF file is inside some folder and that folder doesn't have permission to access files in that folder directly then you have to bypass some file access restrictions using .htaccess file setting by this way:

<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
    Order Allow,Deny
    Allow from all
</FilesMatch>

But now allow just certain necessary files.

I have used this code and it worked perfectly.

How can you create multiple cursors in Visual Studio Code

Try Ctrl+Alt+Shift+? / ?, without mouse, or hold "alt" and click on all the lines you want.

Note: Tested on Windows.

Difference between database and schema

Database is like container of data with schema, and schemas is layout of the tables there data types, relations and stuff

CSS background-size: cover replacement for Mobile Safari

html body {
  background: url(/assets/images/header-bg.jpg) no-repeat top center fixed;
  width: 100%;
  height: 100%;
  min-width: 100%;
  min-height: 100%;

  -webkit-background-size: auto auto;
  -moz-background-size: auto auto;
  -o-background-size: auto auto;
  background-size: auto auto;
}

Google Chromecast sender error if Chromecast extension is not installed or using incognito

By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

I had a similar problem using Tomcat against Oracle. I DID have the context.xml in the META-INF directory, on the disc. This file was not showing in the eclipse project though. A simple hit on the F5 refresh and the context.xml file appeared and eclipse published it. Everything worked past that. Hope this helps someone.

Try hitting F5 in eclipse

String.Format alternative in C++

The C++ way would be to use a std::stringstream object as:

std::stringstream fmt;
fmt << a << " " << b << " > " << c;

The C way would be to use sprintf.

The C way is difficult to get right since:

  • It is type unsafe
  • Requires buffer management

Of course, you may want to fall back on the C way if performance is an issue (imagine you are creating fixed-size million little stringstream objects and then throwing them away).

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

How to remove trailing whitespaces with sed?

Just for fun:

#!/bin/bash

FILE=$1

if [[ -z $FILE ]]; then
   echo "You must pass a filename -- exiting" >&2
   exit 1
fi

if [[ ! -f $FILE ]]; then
   echo "There is not file '$FILE' here -- exiting" >&2
   exit 1
fi

BEFORE=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`

# >>>>>>>>>>
sed -i.bak -e's/[ \t]*$//' "$FILE"
# <<<<<<<<<<

AFTER=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`

if [[ $? != 0 ]]; then
   echo "Some error occurred" >&2
else
   echo "Filtered '$FILE' from $BEFORE characters to $AFTER characters"
fi

PHP check whether property exists in object or class

property_exists( mixed $class , string $property )

if (property_exists($ob, 'a')) 

isset( mixed $var [, mixed $... ] )

if (isset($ob->a))

isset() will return false if property is null

Example 1:

$ob->a = null
var_dump(isset($ob->a)); // false

Example 2:

class Foo
{
   public $bar = null;
}

$foo = new Foo();

var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false

C++ - Assigning null to a std::string

The else case is unncecessary, when you create a string object it is empty by default.

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

I solve that with putting this at the end of my app module build.gradle:

    configurations.all {
     resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '26.0.0'
        }
    }
  }
}

What does the following Oracle error mean: invalid column index

Using Spring's SimpleJdbcTemplate, I got it when I tried to do this:

String sqlString = "select pwy_code from approver where university_id = '123'";
List<Map<String, Object>> rows = getSimpleJdbcTemplate().queryForList(sqlString, uniId);
  • I had an argument to queryForList that didn't correspond to a question mark in the SQL. The first line should have been:

    String sqlString = "select pwy_code from approver where university_id = ?";
    

Installing MySQL Python on Mac OS X

Above all, I can't solve it. But I add file to /usr/local/include solve it.

https://github.com/peterlee0304/MySQL-Python/blob/master/my_config.h

In /usr/local/include, add a my_config.h file.

Then pip install MySQL-Python

Solve it!

JavaScript: function returning an object

Both styles, with a touch of tweaking, would work.

The first method uses a Javascript Constructor, which like most things has pros and cons.

 // By convention, constructors start with an upper case letter
function MakePerson(name,age) {
  // The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
  this.name = name;
  this.age = age;
  this.occupation = "Hobo";
}
var jeremy = new MakePerson("Jeremy", 800);

On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.

function makePerson(name2, age2) {
  var name = name2;
  var age = age2;

  return {
    name: name,
    age: age
  };
}

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

Even if fileno(FILE *) may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.

To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)

Disable ONLY_FULL_GROUP_BY

If you are using MySQL 8.0.11 so, you need to remove the ’NO_AUTO_CREATE_USER‘ from sql-mode.

Add following line in file /etc/mysql/my.cnf and [mysqld] header

[mysqld]

sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

View contents of database file in Android Studio

Simple and easy way to see database content within Android studio.

#For Android Studio 4.1 Canary 6 and higher

You can use a very simple Android Studio's feature Database Inspector. Where you can inspect, query, and modify your app’s databases using the new Database Inspector. For example, you can debug your running app by modifying values in your database and testing those changes on the device in real-time without leaving Android Studio.

To get started, deploy your app to a device running API level 26 or higher and select View > Tool Windows > Database Inspector from the menu bar.

#For Android Studio 4.0 and lesser

First, install Database Navigator plugin in Android Studio

enter image description here

Second, Restart Android Studio

Third, save the database into the default location like: (C:\Users\User Name\Documents\AndroidStudio\DeviceExplorer\emulator or device\data\data\package name\databases)

enter image description here

Fourth, Connect saved dbname_db file in Database Navigator

enter image description here enter image description here

Give same DB file path that is used in step Third

i.e (C:\Users\User Name\Documents\AndroidStudio\DeviceExplorer\emulator or device\data\data\package name\databases\package naem\dbname_db)

Finally, just test DB connection and open console and do whatever you want to do.

enter image description here

If you want to refresh DB just repeat step Second and just save it or refresh.

HAPPY CODING!!!!!

Convert array of indices to 1-hot encoded numpy array

If using tensorflow, there is one_hot():

import tensorflow as tf
import numpy as np

a = np.array([1, 0, 3])
depth = 4
b = tf.one_hot(a, depth)
# <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
# array([[0., 1., 0.],
#        [1., 0., 0.],
#        [0., 0., 0.]], dtype=float32)>

How to vertically align text in input type="text"?

Use padding to fake it since vertical-align doesn't work on text inputs.

jsFiddle example

CSS

.date-input {     
    width: 145px;
    padding-top: 80px;
}?

How to hide a div element depending on Model value? MVC

Your code isn't working, because the hidden attibute is not supported in versions of IE before v11

If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:

*[hidden] { display: none; }

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

I think its a bug, please apply the workaround and then try again: http://support.microsoft.com/kb/281517.

Also, go into Advanced tab, and confirm if Target columns length is Varchar(max).

How to have an auto incrementing version number (Visual Studio)?

You could use the T4 templating mechanism in Visual Studio to generate the required source code from a simple text file :

I wanted to configure version information generation for some .NET projects. It’s been a long time since I investigated available options, so I searched around hoping to find some simple way of doing this. What I’ve found didn’t look very encouraging: people write Visual Studio add-ins and custom MsBuild tasks just to obtain one integer number (okay, maybe two). This felt overkill for a small personal project.

The inspiration came from one of the StackOverflow discussions where somebody suggested that T4 templates could do the job. And of course they can. The solution requires a minimal effort and no Visual Studio or build process customization. Here what should be done:

  1. Create a file with extension ".tt" and place there T4 template that will generate AssemblyVersion and AssemblyFileVersion attributes:
<#@ template language="C#" #>
// 
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// 

using System.Reflection;

[assembly: AssemblyVersion("1.0.1.<#= this.RevisionNumber #>")]
[assembly: AssemblyFileVersion("1.0.1.<#= this.RevisionNumber #>")]
<#+
    int RevisionNumber = (int)(DateTime.UtcNow - new DateTime(2010,1,1)).TotalDays;
#>

You will have to decide about version number generation algorithm. For me it was sufficient to auto-generate a revision number that is set to the number of days since January 1st, 2010. As you can see, the version generation rule is written in plain C#, so you can easily adjust it to your needs.

  1. The file above should be placed in one of the projects. I created a new project with just this single file to make version management technique clear. When I build this project (actually I don’t even need to build it: saving the file is enough to trigger a Visual Studio action), the following C# is generated:
// 
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// 

using System.Reflection;

[assembly: AssemblyVersion("1.0.1.113")]
[assembly: AssemblyFileVersion("1.0.1.113")]

Yes, today it’s 113 days since January 1st, 2010. Tomorrow the revision number will change.

  1. Next step is to remove AssemblyVersion and AssemblyFileVersion attributes from AssemblyInfo.cs files in all projects that should share the same auto-generated version information. Instead choose “Add existing item” for each projects, navigate to the folder with T4 template file, select corresponding “.cs” file and add it as a link. That will do!

What I like about this approach is that it is lightweight (no custom MsBuild tasks), and auto-generated version information is not added to source control. And of course using C# for version generation algorithm opens for algorithms of any complexity.

`IF` statement with 3 possible answers each based on 3 different ranges

Your formula should be of the form =IF(X2 >= 85,0.559,IF(X2 >= 80,0.327,IF(X2 >=75,0.255,0))). This simulates the ELSE-IF operand Excel lacks. Your formulas were using two conditions in each, but the second parameter of the IF formula is the value to use if the condition evaluates to true. You can't chain conditions in that manner.

Convert bytes to a string

I think this way is easy:

>>> bytes_data = [112, 52, 52]
>>> "".join(map(chr, bytes_data))
'p44'

How to convert an array to object in PHP?

Depending on where you need that and how to access the object there are different ways to do it.

For example: just typecast it

$object =  (object) $yourArray;

However, the most compatible one is using a utility method (not yet part of PHP) that implements standard PHP casting based on a string that specifies the type (or by ignoring it just de-referencing the value):

/**
 * dereference a value and optionally setting its type
 *
 * @param mixed $mixed
 * @param null  $type (optional)
 *
 * @return mixed $mixed set as $type
 */
function rettype($mixed, $type = NULL) {
    $type === NULL || settype($mixed, $type);
    return $mixed;
}

The usage example in your case (Online Demo):

$yourArray = Array('status' => 'Figure A. ...');

echo rettype($yourArray, 'object')->status; // prints "Figure A. ..."

How to convert JSONObjects to JSONArray?

Your response should be something like this to be qualified as Json Array.

{
  "songs":[
    {"2562862600": {"id":"2562862600", "pos":1}},  
    {"2562862620": {"id":"2562862620", "pos":1}},  
    {"2562862604": {"id":"2562862604", "pos":1}},  
    {"2573433638": {"id":"2573433638", "pos":1}}
  ]
}

You can parse your response as follows

String resp = ...//String output from your source
JSONObject ob = new JSONObject(resp);  
JSONArray arr = ob.getJSONArray("songs");

for(int i=0; i<arr.length(); i++){   
  JSONObject o = arr.getJSONObject(i);  
  System.out.println(o);  
}

Simple Deadlock Examples

Here's a simple example in C++11.

#include <mutex>    // mutex
#include <iostream> // cout 
#include <cstdio>   // getchar
#include <thread>   // this_thread, yield
#include <future>   // async
#include <chrono>   // seconds

using namespace std;
mutex _m1;
mutex _m2;

// Deadlock will occur because func12 and func21 acquires the two locks in reverse order

void func12()
{
    unique_lock<mutex> l1(_m1);
    this_thread::yield(); // hint to reschedule
    this_thread::sleep_for( chrono::seconds(1) );
    unique_lock<mutex> l2(_m2 );
}

void func21()
{
    unique_lock<mutex> l2(_m2);
    this_thread::yield(); // hint to reschedule
    this_thread::sleep_for( chrono::seconds(1) );
    unique_lock<mutex> l1(_m1);
}

int main( int argc, char* argv[] )
{
    async(func12);
    func21();
    cout << "All done!"; // this won't be executed because of deadlock
    getchar();
}

Stop form from submitting , Using Jquery

use this too :

if(e.preventDefault) 
   e.preventDefault(); 
else 
   e.returnValue = false;

Becoz e.preventDefault() is not supported in IE( some versions ). In IE it is e.returnValue = false

CSS: How to position two elements on top of each other, without specifying a height?

First of all, you really should be including the position on absolutely positioned elements or you will come across odd and confusing behavior; you probably want to add top: 0; left: 0 to the CSS for both of your absolutely positioned elements. You'll also want to have position: relative on .container_row if you want the absolutely positioned elements to be positioned with respect to their parent rather than the document's body:

If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed' ...

Your problem is that position: absolute removes elements from the normal flow:

It is removed from the normal flow entirely (it has no impact on later siblings). An absolutely positioned box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants. However, the contents of an absolutely positioned element do not flow around any other boxes.

This means that absolutely positioned elements have no effect whatsoever on their parent element's size and your first <div class="container_row"> will have a height of zero.

So you can't do what you're trying to do with absolutely positioned elements unless you know how tall they're going to be (or, equivalently, you can specify their height). If you can specify the heights then you can put the same heights on the .container_row and everything will line up; you could also put a margin-top on the second .container_row to leave room for the absolutely positioned elements. For example:

http://jsfiddle.net/ambiguous/zVBDc/

Ant task to run an Ant target only if a file exists?

I think its worth referencing this similar answer: https://stackoverflow.com/a/5288804/64313

Here is a another quick solution. There are other variations possible on this using the <available> tag:

# exit with failure if no files are found
<property name="file" value="${some.path}/some.txt" />
<fail message="FILE NOT FOUND: ${file}">
    <condition><not>
        <available file="${file}" />
    </not></condition>
</fail>

Getting the last revision number in SVN?

Update: Subversion 1.9 will support a new command "svn youngest" that outputs only the latest revision number. The difference to "svnlook youngest" is that "svn youngest" also works remotely.

http://subversion.tigris.org/issues/show_bug.cgi?id=4299

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

How to work with complex numbers in C?

To extract the real part of a complex-valued expression z, use the notation as __real__ z. Similarly, use __imag__ attribute on the z to extract the imaginary part.

For example;

__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;

r is the real part of the complex number "z" i is the imaginary part of the complex number "z"

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Don't forget to add sudo otherwise you will get postman.tar.gz: Permission denied error. And unlink postman if you get error like failed to create symbolic link /usr/bin/postman: File exists. So below is the full code:

sudo wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
sudo tar -xzf postman.tar.gz -C /opt
sudo rm postman.tar.gz

sudo unlink /usr/bin/postman
sudo ln -s /opt/Postman/Postman /usr/bin/postman

Then just run postman in the terminal.

Static nested class in Java, why?

The Sun page you link to has some key differences between the two:

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
...

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

There is no need for LinkedList.Entry to be top-level class as it is only used by LinkedList (there are some other interfaces that also have static nested classes named Entry, such as Map.Entry - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.

As Jon Skeet points out, I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

I have debian 9 and to fix this i used the new library as follows:

ln -s /usr/bin/gpgv /usr/bin/gnupg2

How can I ssh directly to a particular directory?

You could add

cd /some/directory/somewhere/named/Foo

to your .bashrc file (or .profile or whatever you call it) at the other host. That way, no matter what you do or where you ssh from, whenever you log onto that server, it will cd to the proper directory for you, and all you have to do is use ssh like normal.

Of curse, rogeriopvl's solution works too, but it's a tad bit more verbose, and you have to remember to do it every time (unless you make an alias) so it seems a bit less "fun".

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

How to see my Eclipse version?

Go to Help -> About Eclipse Sdk

enter image description here

enter image description here

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

What is char ** in C?

well, char * means a pointer point to char, it is different from char array.

char amessage[] = "this is an array";  /* define an array*/
char *pmessage = "this is a pointer"; /* define a pointer*/

And, char ** means a pointer point to a char pointer.

You can look some books about details about pointer and array.

Unix shell script find out which directory the script file resides?

This one-liner tells where the shell script is, does not matter if you ran it or if you sourced it. Also, it resolves any symbolic links involved, if that is the case:

dir=$(dirname $(test -L "$BASH_SOURCE" && readlink -f "$BASH_SOURCE" || echo "$BASH_SOURCE"))

By the way, I suppose you are using /bin/bash.

Up, Down, Left and Right arrow keys do not trigger KeyDown event

i had the same problem and was already using the code in the selected answer. this link was the answer for me; maybe for others also.

How to disable navigation on WinForm with arrows in C#?

Google Play Services Missing in Emulator (Android 4.4.2)

If you're using Xamarin, I found a guide on their official forum explaining how to do this:

  1. Download the package from the internet. There are many sources for this, one possible source is the CyanogenMod web site.
  2. Start up the Android Player and unlock it.
  3. Drag and drop the zip file that you downloaded onto the Android Player.
  4. Restart the Android Player.

Hereafter, you might also need to update the Google Play Services from the Google Play Store.

Hope this helps for anyone else who has troubles finding the documentation.

Html.BeginForm and adding properties

You can also use the following syntax for the strongly typed version:

<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(), 
          FormMethod.Post, 
          new { enctype = "multipart/form-data" })) 
   { %>

How can I format decimal property to currency?

Try this;

  string.Format(new CultureInfo("en-SG", false), "{0:c0}", 123423.083234);

It will convert 123423.083234 to $1,23,423 format.

mailto using javascript

Please find the code in jsFiddle. It uses jQuery to modify the href of the link. You can use any other library in its place. It should work.

HTML

<a id="emailLnk" href="#">
    <img src="http://ssl.gstatic.com/gb/images/j_e6a6aca6.png">
</a>

JS

$(document).ready(function() {
    $("#emailLnk").attr('href',"mailto:[email protected]");
});?

UPDATE

Another code sample, if the id is known only during the click event

$(document).ready(function() {
    $("#emailLnk").click(function()
     {
         window.location.href = "mailto:[email protected]";
     });
});?

How can I get customer details from an order in WooCommerce?

Having tried $customer = new WC_Customer(); and global $woocommerce; $customer = $woocommerce->customer; I was still getting empty address data even when I logged in as a non-admin user.

My solution was as follows:

function mwe_get_formatted_shipping_name_and_address($user_id) {

    $address = '';
    $address .= get_user_meta( $user_id, 'shipping_first_name', true );
    $address .= ' ';
    $address .= get_user_meta( $user_id, 'shipping_last_name', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_company', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_address_1', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_address_2', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_city', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_state', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_postcode', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_country', true );

    return $address;
}

...and this code works regardless of whether you are logged in as admin or not.

TypeScript and array reduce function

With TypeScript generics you can do something like this.

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);

When is it appropriate to use C# partial classes?

Another use is to split the implementation of different interfaces, e.g:

partial class MyClass : IF3
{
    // main implementation of MyClass
}


partial class MyClass : IF1
{
    // implementation of IF1
}

partial class MyClass : IF2
{
    // implementation of IF2
}

Get the name of a pandas DataFrame

In many situations, a custom attribute attached to a pd.DataFrame object is not necessary. In addition, note that pandas-object attributes may not serialize. So pickling will lose this data.

Instead, consider creating a dictionary with appropriately named keys and access the dataframe via dfs['some_label'].

df = pd.DataFrame()

dfs = {'some_label': df}

Reverse of JSON.stringify?

http://jsbin.com/tidob/1/edit?js,console,output

The native JSON object includes two key methods.

1. JSON.parse()
2. JSON.stringify() 
  1. The JSON.parse() method parses a JSON string - i.e. reconstructing the original JavaScript object

    var jsObject = JSON.parse(jsonString);

  2. JSON.stringify() method accepts a JavaScript object and returns its JSON equivalent.

    var jsonString = JSON.stringify(jsObject);

Implicit type conversion rules in C++ operators

Arithmetic operations involving float results in float.

int + float = float
int * float = float
float * int = float
int / float = float
float / int = float
int / int = int

For more detail answer. Look at what the section §5/9 from the C++ Standard says

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result.

This pattern is called the usual arithmetic conversions, which are defined as follows:

— If either operand is of type long double, the other shall be converted to long double.

— Otherwise, if either operand is double, the other shall be converted to double.

— Otherwise, if either operand is float, the other shall be converted to float.

— Otherwise, the integral promotions (4.5) shall be performed on both operands.54)

— Then, if either operand is unsigned long the other shall be converted to unsigned long.

— Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.

— Otherwise, if either operand is long, the other shall be converted to long.

— Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

[Note: otherwise, the only remaining case is that both operands are int ]

How do I prevent and/or handle a StackOverflowException?

With .NET 4.0 You can add the HandleProcessCorruptedStateExceptions attribute from System.Runtime.ExceptionServices to the method containing the try/catch block. This really worked! Maybe not recommended but works.

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;

namespace ExceptionCatching
{
    public class Test
    {
        public void StackOverflow()
        {
            StackOverflow();
        }

        public void CustomException()
        {
            throw new Exception();
        }

        public unsafe void AccessViolation()
        {
            byte b = *(byte*)(8762765876);
        }
    }

    class Program
    {
        [HandleProcessCorruptedStateExceptions]
        static void Main(string[] args)
        {
            Test test = new Test();
            try {
                //test.StackOverflow();
                test.AccessViolation();
                //test.CustomException();
            }
            catch
            {
                Console.WriteLine("Caught.");
            }

            Console.WriteLine("End of program");

        }

    }      
}

ReactJS lifecycle method inside a function Component

You can use react-pure-lifecycle to add lifecycle functions to functional components.

Example:

import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';

const methods = {
  componentDidMount(props) {
    console.log('I mounted! Here are my props: ', props);
  }
};

const Channels = props => (
<h1>Hello</h1>
)

export default lifecycle(methods)(Channels);

Reporting Services Remove Time from DateTime in Expression

=CDate(Now).ToString("dd/MM/yyyy")

Although you are hardcoding the date formart to a locale.

preg_match in JavaScript?

Sample code to get image links within HTML content. Like preg_match_all in PHP

let HTML = '<div class="imageset"><table><tbody><tr><td width="50%"><img src="htt ps://domain.com/uploads/monthly_2019_11/7/1.png.jpg" class="fr-fic fr-dii"></td><td width="50%"><img src="htt ps://domain.com/uploads/monthly_2019_11/7/9.png.jpg" class="fr-fic fr-dii"></td></tr></tbody></table></div>';
let re = /<img src="(.*?)"/gi;
let result = HTML.match(re);

out array

0: "<img src="htt ps://domain.com/uploads/monthly_2019_11/7/1.png.jpg""
1: "<img src="htt ps://domain.com/uploads/monthly_2019_11/7/9.png.jpg""

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

POSIX 7 quotes

POSIX 7 specifies both at http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html:

CLOCK_REALTIME:

This clock represents the clock measuring real time for the system. For this clock, the values returned by clock_gettime() and specified by clock_settime() represent the amount of time (in seconds and nanoseconds) since the Epoch.

CLOCK_MONOTONIC (optional feature):

For this clock, the value returned by clock_gettime() represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time. The value of the CLOCK_MONOTONIC clock cannot be set via clock_settime().

clock_settime() gives an important hint: POSIX systems are able to arbitrarily change CLOCK_REALITME with it, so don't rely on it flowing neither continuously nor forward. NTP could be implemented using clock_settime(), and could only affect CLOCK_REALITME.

The Linux kernel implementation seems to take boot time as the epoch for CLOCK_MONOTONIC: Starting point for CLOCK_MONOTONIC

How to select first child with jQuery?

As @Roko mentioned you can do this in multiple ways.

1.Using the jQuery first-child selector - SnoopCode

   $(document).ready(function(){
    $(".alldivs onediv:first-child").css("background-color","yellow");
        }
  1. Using jQuery eq Selector - SnoopCode

     $( "body" ).find( "onediv" ).eq(1).addClass( "red" );
    
  2. Using jQuery Id Selector - SnoopCode

       $(document).ready(function(){
         $("#div1").css("background-color: red;");
       });
    

Difference between an API and SDK

Suppose company C offers product P and P involves software in some way. Then C can offer a library/set of libraries to software developers that drive P's software systems.

That library/libraries are an SDK. It is part of the systems of P. It is a kit for software developers to use in order to modify, configure, fix, improve, etc the software piece of P.

If C wants to offer P's functionality to other companies/systems, it does so with an API.

This is an interface to P. A way for external systems to interact with P.

If you think in terms of implementation, they will seem quite similar. Especially now that the internet has become like one large distributed operating system.

In purpose, though, they are actually quite distinct.

You build something with an SDK and you use or consume something with an API.

node.js, socket.io with SSL

For enterprise applications it should be noted that you should not be handling https in your code. It should be auto upgraded via IIS or nginx. The app shouldn't know about what protocols are used.

How to store decimal values in SQL Server?

The settings for Decimal are its precision and scale or in normal language, how many digits can a number have and how many digits do you want to have to the right of the decimal point.

So if you put PI into a Decimal(18,0) it will be recorded as 3?

If you put PI into a Decimal(18,2) it will be recorded as 3.14?

If you put PI into Decimal(18,10) be recorded as 3.1415926535.

PHP Date Time Current Time Add Minutes

This is an old question that seems answered, but as someone pointed out above, if you use the DateTime class and PHP < 5.3.0, you can't use the add method, but you can use modify:

$date = new DateTime();
$date->modify("+30 minutes"); //or whatever value you want

Tomcat: How to find out running tomcat version

Enter 404.jsp or non-existent.jsp.

Get Tomcat/JBoss version number at bottom of page.

Find out where MySQL is installed on Mac OS X

If you run SHOW VARIABLES from a mysql console you can look for basedir.

When I run the following:

mysql> SHOW VARIABLES WHERE `Variable_name` = 'basedir';

on my system I get /usr/local/mysql as the Value returned. (I am not using MAMP - I installed MySQL with homebrew.

mysqldon my machine is in /usr/local/mysql/bin so the basedir is where most everything will be installed to.

Also util:

mysql> SHOW VARIABLES WHERE `Variable_name` = 'datadir'; 

To find where the DBs are stored.

For more: http://dev.mysql.com/doc/refman/5.0/en/show-variables.html

and http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_basedir

iOS Launching Settings -> Restrictions URL Scheme

In iOS 9 it works again!

To open Settings > General > Keyboard, I use:

prefs:root=General&path=Keyboard

Moreover, it is possible to go farther to Keyboards:

prefs:root=General&path=Keyboard/KEYBOARDS

Force IE9 to emulate IE8. Possible?

Yes. Recent versions of IE (IE8 or above) let you adjust that. Here's how:

  • Fire up Internet Explorer.
  • Click the 'Tools' menu, then click 'Developer Tools'. Alternatively, just press F12.

That should open the Developer Tools window. That window has two menu items that are of interest:

  • Browser Mode. This setting determines the value of the user-agent header sent for every request.
  • Document Mode. This setting determines how the rendering engine renders the page.

More at http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

No need for array. Just use something like this:

Sub ARRAYER()

    Dim Rng As Range
    Dim Number_of_Sims As Long
    Dim i As Long
    Number_of_Sims = 10

    Set Rng = Range("C4:G4")
    For i = 1 To Number_of_Sims
       Rng.Offset(i, 0).Value = Rng.Value
       Worksheets("Sheetname").Calculate   'replacing Sheetname with name of your sheet
    Next

End Sub

What is the difference between a mutable and immutable string in C#?

String is immutable

i.e. strings cannot be altered. When you alter a string (by adding to it for example), you are actually creating a new string.

But StringBuilder is not immutable (rather, it is mutable)

so if you have to alter a string many times, such as multiple concatenations, then use StringBuilder.

The connection to adb is down, and a severe error has occurred

I restarted eclipse and did the Project -> Clean -> select your project One of them fixed my problem with adb

[2011-12-31 10:50:45 - HelloAndroid] Android Launch!                      good

[2011-12-31 10:50:45 - HelloAndroid] adb is running normally.             good

[2011-12-31 10:50:45 - HelloAndroid] Could not find HelloAndroid.apk!     bad

Thanks for the help. On to the next problem (sigh)

What is ".NET Core"?

.NET Core is an open source and cross platform version of .NET Framework.

How to write URLs in Latex?

You can use \url

\usepackage{hyperref}
\url{http://stackoverflow.com/}

Process to convert simple Python script into Windows executable

you may want to see if your app can run under IronPython. If so, you can compile it to an exe http://www.codeplex.com/IronPython

Clear MySQL query cache without restarting server

I believe you can use...

RESET QUERY CACHE;

...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...

FLUSH QUERY CACHE;

See the Query Cache Status and Maintenance section of the MySQL manual for more information.

Div with horizontal scrolling only

overflow-x: scroll;
overflow-y: hidden;

EDIT:

It works for me:

<div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
    <div style='width:400px;height:250px'></div>
</div>

Ways to iterate over a list in Java

Example of each kind listed in the question:

ListIterationExample.java

import java.util.*;

public class ListIterationExample {

     public static void main(String []args){
        List<Integer> numbers = new ArrayList<Integer>();

        // populates list with initial values
        for (Integer i : Arrays.asList(0,1,2,3,4,5,6,7))
            numbers.add(i);
        printList(numbers);         // 0,1,2,3,4,5,6,7

        // replaces each element with twice its value
        for (int index=0; index < numbers.size(); index++) {
            numbers.set(index, numbers.get(index)*2); 
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14

        // does nothing because list is not being changed
        for (Integer number : numbers) {
            number++; // number = new Integer(number+1);
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14  

        // same as above -- just different syntax
        for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            number++;
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14

        // ListIterator<?> provides an "add" method to insert elements
        // between the current element and the cursor
        for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            iter.add(number+1);     // insert a number right before this
        }
        printList(numbers);         // 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15

        // Iterator<?> provides a "remove" method to delete elements
        // between the current element and the cursor
        for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            if (number % 2 == 0)    // if number is even 
                iter.remove();      // remove it from the collection
        }
        printList(numbers);         // 1,3,5,7,9,11,13,15

        // ListIterator<?> provides a "set" method to replace elements
        for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            iter.set(number/2);     // divide each element by 2
        }
        printList(numbers);         // 0,1,2,3,4,5,6,7
     }

     public static void printList(List<Integer> numbers) {
        StringBuilder sb = new StringBuilder();
        for (Integer number : numbers) {
            sb.append(number);
            sb.append(",");
        }
        sb.deleteCharAt(sb.length()-1); // remove trailing comma
        System.out.println(sb.toString());
     }
}

Open another page in php

<?php
    header("Location: index.html");
?>

Just make sure nothing is actually written to the page prior to this code, or it won't work.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

EncodeAndSend is not a static function, which means it can be called on an instance of the class CPMSifDlg. You cannot write this:

 CPMSifDlg::EncodeAndSend(/*...*/);  //wrong - EncodeAndSend is not static

It should rather be called as:

 CPMSifDlg dlg; //create instance, assuming it has default constructor!
 dlg.EncodeAndSend(/*...*/);   //correct 

Set CFLAGS and CXXFLAGS options using CMake

You need to set the flags after the project command in your CMakeLists.txt.

Also, if you're calling include(${QT_USE_FILE}) or add_definitions(${QT_DEFINITIONS}), you should include these set commands after the Qt ones since these would append further flags. If that is the case, you maybe just want to append your flags to the Qt ones, so change to e.g.

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb")

Throwing exceptions from constructors

Adding to all the answers here, I thought to mention, a very specific reason/scenario where you might want to prefer to throw the exception from the class's Init method and not from the Ctor (which off course is the preferred and more common approach).

I will mention in advance that this example (scenario) assumes that you don't use "smart pointers" (i.e.- std::unique_ptr) for your class' s pointer(s) data members.

So to the point: In case, you wish that the Dtor of your class will "take action" when you invoke it after (for this case) you catch the exception that your Init() method threw - you MUST not throw the exception from the Ctor, cause a Dtor invocation for Ctor's are NOT invoked on "half-baked" objects.

See the below example to demonstrate my point:

#include <iostream>

using namespace std;

class A
{
    public:
    A(int a)
        : m_a(a)
    {
        cout << "A::A - setting m_a to:" << m_a << endl;
    }

    ~A()
    {
        cout << "A::~A" << endl;
    }

    int m_a;
};

class B
{
public:
    B(int b)
        : m_b(b)
    {
        cout << "B::B - setting m_b to:" << m_b << endl;
    }

    ~B()
    {
        cout << "B::~B" << endl;
    }

    int m_b;
};

class C
{
public:
    C(int a, int b, const string& str)
        : m_a(nullptr)
        , m_b(nullptr)
        , m_str(str)
    {
        m_a = new A(a);
        cout << "C::C - setting m_a to a newly A object created on the heap (address):" << m_a << endl;
        if (b == 0)
        {
            throw exception("sample exception to simulate situation where m_b was not fully initialized in class C ctor");
        }

        m_b = new B(b);
        cout << "C::C - setting m_b to a newly B object created on the heap (address):" << m_b << endl;
    }

    ~C()
    {
        delete m_a;
        delete m_b;
        cout << "C::~C" << endl;
    }

    A* m_a;
    B* m_b;
    string m_str;
};

class D
{
public:
    D()
        : m_a(nullptr)
        , m_b(nullptr)
    {
        cout << "D::D" << endl;
    }

    void InitD(int a, int b)
    {
        cout << "D::InitD" << endl;
        m_a = new A(a);
        throw exception("sample exception to simulate situation where m_b was not fully initialized in class D Init() method");
        m_b = new B(b);
    }

    ~D()
    {
        delete m_a;
        delete m_b;
        cout << "D::~D" << endl;
    }

    A* m_a;
    B* m_b;
};

void item10Usage()
{
    cout << "item10Usage - start" << endl;

    // 1) invoke a normal creation of a C object - on the stack
    // Due to the fact that C's ctor throws an exception - its dtor
    // won't be invoked when we leave this scope
    {
        try
        {
            C c(1, 0, "str1");
        }
        catch (const exception& e)
        {
            cout << "item10Usage - caught an exception when trying to create a C object on the stack:" << e.what() << endl;
        }
    }

    // 2) same as in 1) for a heap based C object - the explicit call to 
    //    C's dtor (delete pc) won't have any effect
    C* pc = 0;
    try
    {
        pc = new C(1, 0, "str2");
    }
    catch (const exception& e)
    {
        cout << "item10Usage - caught an exception while trying to create a new C object on the heap:" << e.what() << endl;
        delete pc; // 2a)
    }

    // 3) Here, on the other hand, the call to delete pd will indeed 
    //    invoke D's dtor
    D* pd = new D();
    try
    {
        pd->InitD(1,0);
    }
    catch (const exception& e)
    {
        cout << "item10Usage - caught an exception while trying to init a D object:" << e.what() << endl;
        delete pd; 
    }

    cout << "\n \n item10Usage - end" << endl;
}

int main(int argc, char** argv)
{
    cout << "main - start" << endl;
    item10Usage();
    cout << "\n \n main - end" << endl;
    return 0;
}

I will mention again, that it is not the recommended approach, just wanted to share an additional point of view.

Also, as you might have seen from some of the print in the code - it is based on item 10 in the fantastic "More effective C++" by Scott Meyers (1st edition).

Need to combine lots of files in a directory

Yes , A plugin is available named "combine" for notepad++.Link: .>> Combine Plugin for Notepad++

You can install it via plugin manager. Extra benifit of this plugin is: "You can maintain the sequence of files while merging, it's according to the sequence of opened files are opened (see tabs)".

Woocommerce, get current product id

Retrieve the ID of the current item in the WordPress Loop.

echo get_the_ID(); 

hence works for the product id too. #tested #woo-commerce

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

How to import existing *.sql files in PostgreSQL 8.4?

From the command line:

psql -f 1.sql
psql -f 2.sql

From the psql prompt:

\i 1.sql
\i 2.sql

Note that you may need to import the files in a specific order (for example: data definition before data manipulation). If you've got bash shell (GNU/Linux, Mac OS X, Cygwin) and the files may be imported in the alphabetical order, you may use this command:

for f in *.sql ; do psql -f $f ; done

Here's the documentation of the psql application (thanks, Frank): http://www.postgresql.org/docs/current/static/app-psql.html

How do I disable right click on my web page?

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(function(){
$('img').bind('contextmenu', function(e){
return false;
}); 
});//]]>  
</script>
</head>
<body>
    <img src="http://www.winergyinc.com/wp-content/uploads/2010/12/ajax.jpg"/>
</body>

How to access List elements

I'd start by not calling it list, since that's the name of the constructor for Python's built in list type.

But once you've renamed it to cities or something, you'd do:

print(cities[0][0], cities[1][0])
print(cities[0][1], cities[1][1])

Spring .properties file: get element as an Array

With a Spring Boot one can do the following:

application.properties

values[0]=abc
values[1]=def

Configuration class

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

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

@Component
@ConfigurationProperties
public class Configuration {

    List<String> values = new ArrayList<>();

    public List<String> getValues() {
        return values;
    }

}

This is needed, without this class or without the values in class it is not working.

Spring Boot Application class

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.List;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory.getLogger(SpringBootConsoleApplication.class);

    // notice #{} is used instead of ${}
    @Value("#{configuration.values}")
    List<String> values;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootConsoleApplication.class, args);
    }

    @Override
    public void run(String... args) {
        LOG.info("values: {}", values);
    }

}

How to declare string constants in JavaScript?

So many ways to skin this cat. You can do this in a closure. This code will give you a read-only , namespaced way to have constants. Just declare them in the Public area.

//Namespaced Constants
var MyAppName;
//MyAppName Namespace
(function (MyAppName) {
    //MyAppName.Constants Namespace
    (function (Constants) {
        //Private
        function createConstant(name, val) {
            Object.defineProperty(MyAppName.Constants, name, {
                value: val,
                writable: false
            });
        }

        //Public
        Constants.FOO = createConstant("FOO", 1);
        Constants.FOO2 = createConstant("FOO2", 1);

        MyAppName.Constants = Constants;
    })(MyAppName.Constants || (MyAppName.Constants = {}));
})(MyAppName || (MyAppName = {}));

Usage:

console.log(MyAppName.Constants.FOO);       //prints 1
MyAppName.Constants.FOO = 2;
console.log(MyAppName.Constants.FOO);       //does not change - still prints 1

how to remove the bold from a headline?

<h1><span>This is</span> a Headline</h1>

h1 { font-weight: normal; text-transform: uppercase; }
h1 span { font-weight: bold; }

I'm not sure if it was just for the sake of showing us, but as a side note, you should always set uppercase text with CSS :)

Intel's HAXM equivalent for AMD on Windows OS

Posting a new answer since it is (almost) 2020.

The Android Emulator still only supports HAXM or WHPX on windows. And you may even call it a day already with the latter.

But if you don't like it, there is now work in progress AMD-V support for the former by one of the PS4 emulator developers: https://github.com/jarveson/haxm/tree/svm

Resetting a form in Angular 2 after submit

Please use The following format, its working perfectly for me..i have checked lot ways but this works perfectly.<form (ngSubmit)="mySubmitHandler(); myNgForm.resetForm()" #myNgForm="ngForm"> .... </form>

How to use the 'replace' feature for custom AngularJS directives?

replace:true is Deprecated

From the Docs:

replace ([DEPRECATED!], will be removed in next major release - i.e. v2.0)

specify what the template should replace. Defaults to false.

  • true - the template will replace the directive's element.
  • false - the template will replace the contents of the directive's element.

-- AngularJS Comprehensive Directive API

From GitHub:

Caitp-- It's deprecated because there are known, very silly problems with replace: true, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".

-- AngularJS Issue #7636


Update

Note: replace: true is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.

Issues with replace: true

For more information, see

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

For Vb.Net Framework 4.0, U can use:

Alert("your message here", Boolean)

The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

Try conda install -c conda-forge opencv if you are using anaconda, it works!

Android: show/hide status bar/power bar

fun Activity.setStatusBarVisibility(isVisible: Boolean) {
    //see details https://developer.android.com/training/system-ui/immersive
    if (isVisible) {
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    } else {
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_FULLSCREEN)
    }
}

How do I pass environment variables to Docker containers?

The problem I had was that I was putting the --env-file at the end of the command

docker run -it --rm -p 8080:80 imagename --env-file ./env.list

Fix

docker run --env-file ./env.list -it --rm -p 8080:80 imagename

How to get the cell value by column name not by index in GridView in asp.net

Header Row cells sometimes will not work. This will just return the column Index. It will help in a lot of different ways. I know this is not the answer he is requesting. But this will help for a lot people.

public static int GetColumnIndexByHeaderText(GridView gridView, string columnName)
    {      
        for (int i = 0; i < gridView.Columns.Count ; i++)
        {
            if (gridView.Columns[i].HeaderText.ToUpper() == columnName.ToUpper() )
            {
                return i;
            }
        }     
        return -1;
    }

Java 6 Unsupported major.minor version 51.0

add jdk8 or higher version at JAVA_HOME and path.

add JAVA_HOME add C:\ProgramFiles\Java\jdk1.8.0_201

For Path =>

add %MAVEN_HOME%\bin

and finally restart your pc.

How do I pass parameters into a PHP script through a webpage?

$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter

If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

<?php
if ($_GET) {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
} else {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
?>

To call from command line chmod 755 /var/www/webroot/index.php and use

/usr/bin/php /var/www/webroot/index.php arg1 arg2

To call from the browser, use

http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2

Pretty Printing a pandas dataframe

Maybe you're looking for something like this:

def tableize(df):
    if not isinstance(df, pd.DataFrame):
        return
    df_columns = df.columns.tolist() 
    max_len_in_lst = lambda lst: len(sorted(lst, reverse=True, key=len)[0])
    align_center = lambda st, sz: "{0}{1}{0}".format(" "*(1+(sz-len(st))//2), st)[:sz] if len(st) < sz else st
    align_right = lambda st, sz: "{0}{1} ".format(" "*(sz-len(st)-1), st) if len(st) < sz else st
    max_col_len = max_len_in_lst(df_columns)
    max_val_len_for_col = dict([(col, max_len_in_lst(df.iloc[:,idx].astype('str'))) for idx, col in enumerate(df_columns)])
    col_sizes = dict([(col, 2 + max(max_val_len_for_col.get(col, 0), max_col_len)) for col in df_columns])
    build_hline = lambda row: '+'.join(['-' * col_sizes[col] for col in row]).join(['+', '+'])
    build_data = lambda row, align: "|".join([align(str(val), col_sizes[df_columns[idx]]) for idx, val in enumerate(row)]).join(['|', '|'])
    hline = build_hline(df_columns)
    out = [hline, build_data(df_columns, align_center), hline]
    for _, row in df.iterrows():
        out.append(build_data(row.tolist(), align_right))
    out.append(hline)
    return "\n".join(out)


df = pd.DataFrame([[1, 2, 3], [11111, 22, 333]], columns=['a', 'b', 'c'])
print tableize(df)
Output:
+-------+----+-----+
|    a  |  b |   c |
+-------+----+-----+
|     1 |  2 |   3 |
| 11111 | 22 | 333 |
+-------+----+-----+

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Fix urlpatterns in urls.py file

For example, my app name is "simulator",

My URL pattern for login and logout looks like

urlpatterns = [
    ...
    ...
    url(r'^login/$', simulator.views.login_view, name="login"),
    url(r'^logout/$', simulator.views.logout_view, name="logout"),
    ...
    ...

]

Bootstrap 3 offset on right not left

Based on WeNeigh's answer! here is a LESS example

.col-offset-right(@i, @type) when (@i >= 0) {
    .col-@{type}-offset-right-@{i} {
        margin-right: percentage((@i / @grid-columns));
    }
    .col-offset-right(@i - 1, @type);
};
.col-offset-right(@grid-columns, xs);
.col-offset-right(@grid-columns, sm);
.col-offset-right(@grid-columns, md);
.col-offset-right(@grid-columns, lg);

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If you set CURLOPT_RETURNTRANSFER to true or 1 then the return value from curl_exec will be the actual result from the successful operation. In other words it will not return TRUE on success. Although it will return FALSE on failure.

As described in the Return Values section of curl-exec PHP manual page: http://php.net/manual/function.curl-exec.php

You should enable the CURLOPT_FOLLOWLOCATION option for redirects but this would be a problem if your server is in safe_mode and/or open_basedir is in effect which can cause issues with curl as well.

How to resolve ORA 00936 Missing Expression Error?

update INC.PROV_CSP_DEMO_ADDR_TEMP pd 
set pd.practice_name = (
    select PRSQ_COMMENT FROM INC.CMC_PRSQ_SITE_QA PRSQ
    WHERE PRSQ.PRSQ_MCTR_ITEM = 'PRNM' 
    AND PRSQ.PRAD_ID = pd.provider_id
    AND PRSQ.PRAD_TYPE = pd.prov_addr_type
    AND ROWNUM = 1
)

CORS with POSTMAN

CORS (Cross-Origin Resource Sharing) and SOP (Same-Origin Policy) are server-side configurations that clients decide to enforce or not.

Related to clients

  • Most Browsers do enforce it to prevent issues related to CSRF attack.
  • Most Development tools don't care about it.

How to make a progress bar

If you are using HTML5 its better to make use of <progress> tag which was newly introduced.

<progress value="22" max="100"></progress>

Or create a progress bar of your own.

Example written in sencha

if (!this.popup) {
            this.popup = new Ext.Panel({
            floating: true,
            modal: false,
            // centered:true,
            style:'background:black;opacity:0.6;margin-top:330px;',
            width: '100%',
            height: '20%',
            styleHtmlContent: true,
            html: '<p align="center" style="color:#FFFFFF;font-size:12px">Downloading Data<hr noshade="noshade"size="7" style="color:#FFFFFF"></p>',

            });
}
this.popup.show('pop');

Intercept page exit event

See this article. The feature you are looking for is the onbeforeunload

sample code:

  <script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>

JVM property -Dfile.encoding=UTF8 or UTF-8?

If, running an Oracle HotSpot JDK 1.7.x, on a Linux platform where your locale suggests UTF-8 (e.g. LANG=en_US.utf8), if you don't set it on the command-line with -Dfile.encoding, the JDK will default file.encoding and the default Charset like this:

System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));

... yields:

file.encoding: UTF-8
defaultCharset: UTF-8

... suggesting the default is UTF-8 on such a platform.

Additionally, if java.nio.charset.Charset.defaultCharset() finds file.encoding not-set, it looks for java.nio.charset.Charset.forName("UTF-8"), suggesting it prefers that string, although it is well-aliased, so "UTF8" will also work fine.

If you run the same program on the same platform with java -Dfile.encoding=UTF8, without the hypen, it yields:

file.encoding: UTF8
defaultCharset: UTF-8

... noting that the default charset has been canonicalized from UTF8 to UTF-8.

ALTER COLUMN in sqlite

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.

  1. BEGIN TRANSACTION;
  2. CREATE TEMPORARY TABLE t1_backup(a,b);
  3. INSERT INTO t1_backup SELECT a,b FROM t1;
  4. DROP TABLE t1;
  5. CREATE TABLE t1(a,b);
  6. INSERT INTO t1 SELECT a,b FROM t1_backup;
  7. DROP TABLE t1_backup;
  8. COMMIT

For more detail you can refer the link.

How to find out what type of a Mat object is with Mat::type() in OpenCV

Here is a handy function you can use to help with identifying your opencv matrices at runtime. I find it useful for debugging, at least.

string type2str(int type) {
  string r;

  uchar depth = type & CV_MAT_DEPTH_MASK;
  uchar chans = 1 + (type >> CV_CN_SHIFT);

  switch ( depth ) {
    case CV_8U:  r = "8U"; break;
    case CV_8S:  r = "8S"; break;
    case CV_16U: r = "16U"; break;
    case CV_16S: r = "16S"; break;
    case CV_32S: r = "32S"; break;
    case CV_32F: r = "32F"; break;
    case CV_64F: r = "64F"; break;
    default:     r = "User"; break;
  }

  r += "C";
  r += (chans+'0');

  return r;
}

If M is a var of type Mat you can call it like so:

string ty =  type2str( M.type() );
printf("Matrix: %s %dx%d \n", ty.c_str(), M.cols, M.rows );

Will output data such as:

Matrix: 8UC3 640x480 
Matrix: 64FC1 3x2 

Its worth noting that there are also Matrix methods Mat::depth() and Mat::channels(). This function is just a handy way of getting a human readable interpretation from the combination of those two values whose bits are all stored in the same value.

Global npm install location on windows?

These are typical npm paths if you install a package globally:

Windows XP -             %USERPROFILE%\Application Data\npm\node_modules
Newer Windows Versions - %AppData%\npm\node_modules
or -                     %AppData%\roaming\npm\node_modules

Why do we have to override the equals() method in Java?

From the article Override equals and hashCode in Java:

Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object.

Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic: example:

many classes in Java standard library does override it e.g. String overrides equals, whose implementation of equals() method return true if content of two String objects are exactly same

Integer wrapper class overrides equals to perform numerical comparison etc.

How to update core-js to core-js@3 dependency?

For npm

 npm install --save core-js@^3

for yarn

yarn add core-js@^3

Is there an auto increment in sqlite?

Beside rowid, you can define your own auto increment field but it is not recommended. It is always be better solution when we use rowid that is automatically increased.

The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.

Read here for detailed information.

Regular expression replace in C#

Try this::

sb_trim = Regex.Replace(stw, @"(\D+)\s+\$([\d,]+)\.\d+\s+(.)",
    m => string.Format(
        "{0},{1},{2}",
        m.Groups[1].Value,
        m.Groups[2].Value.Replace(",", string.Empty),
        m.Groups[3].Value));

This is about as clean an answer as you'll get, at least with regexes.

  • (\D+): First capture group. One or more non-digit characters.
  • \s+\$: One or more spacing characters, then a literal dollar sign ($).
  • ([\d,]+): Second capture group. One or more digits and/or commas.
  • \.\d+: Decimal point, then at least one digit.
  • \s+: One or more spacing characters.
  • (.): Third capture group. Any non-line-breaking character.

The second capture group additionally needs to have its commas stripped. You could do this with another regex, but it's really unnecessary and bad for performance. This is why we need to use a lambda expression and string format to piece together the replacement. If it weren't for that, we could just use this as the replacement, in place of the lambda expression:

"$1,$2,$3"

Regex Explanation ^.*$

  • ^ matches position just before the first character of the string
  • $ matches position just after the last character of the string
  • . matches a single character. Does not matter what character it is, except newline
  • * matches preceding match zero or more times

So, ^.*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.

Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones and Matthew's last name is Jones. The pattern ^Matt.*Jones$ will match Matthew's last name is Jones. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.

Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.

Entity framework self referencing loop detected

I only had one model i wanted to use, so i ended up with the following code:

var JsonImageModel = Newtonsoft.Json.JsonConvert.SerializeObject(Images, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

try using concatenation of string

Statistics(string date)
    {
        this->date += date;
    }

acually this was a part of a class..

Write single CSV file using spark-csv

I might be a little late to the game here, but using coalesce(1) or repartition(1) may work for small data-sets, but large data-sets would all be thrown into one partition on one node. This is likely to throw OOM errors, or at best, to process slowly.

I would highly suggest that you use the FileUtil.copyMerge() function from the Hadoop API. This will merge the outputs into a single file.

EDIT - This effectively brings the data to the driver rather than an executor node. Coalesce() would be fine if a single executor has more RAM for use than the driver.

EDIT 2: copyMerge() is being removed in Hadoop 3.0. See the following stack overflow article for more information on how to work with the newest version: How to do CopyMerge in Hadoop 3.0?

How to check a channel is closed or not without reading it?

I know this answer is so late, I have wrote this solution, Hacking Go run-time, It's not safety, It may crashes:

import (
    "unsafe"
    "reflect"
)


func isChanClosed(ch interface{}) bool {
    if reflect.TypeOf(ch).Kind() != reflect.Chan {
        panic("only channels!")
    }
    
    // get interface value pointer, from cgo_export 
    // typedef struct { void *t; void *v; } GoInterface;
    // then get channel real pointer
    cptr := *(*uintptr)(unsafe.Pointer(
        unsafe.Pointer(uintptr(unsafe.Pointer(&ch)) + unsafe.Sizeof(uint(0))),
    ))
    
    // this function will return true if chan.closed > 0
    // see hchan on https://github.com/golang/go/blob/master/src/runtime/chan.go 
    // type hchan struct {
    // qcount   uint           // total data in the queue
    // dataqsiz uint           // size of the circular queue
    // buf      unsafe.Pointer // points to an array of dataqsiz elements
    // elemsize uint16
    // closed   uint32
    // **
    
    cptr += unsafe.Sizeof(uint(0))*2
    cptr += unsafe.Sizeof(unsafe.Pointer(uintptr(0)))
    cptr += unsafe.Sizeof(uint16(0))
    return *(*uint32)(unsafe.Pointer(cptr)) > 0
}

How to change Navigation Bar color in iOS 7?

If you need to support ios6 and ios7 then you get that particular light blue using this in your UIViewController:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
    if ([[ver objectAtIndex:0] intValue] >= 7) {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:89/255.0f green:174/255.0f blue:235/255.0f alpha:1.0f];
        self.navigationController.navigationBar.translucent = NO;
    }else{
        self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:89/255.0f green:174/255.0f blue:235/255.0f alpha:1.0f];
    }
}

git: Switch branch and ignore any changes without committing

well, it should be

git stash save
git checkout branch
// do something
git checkout oldbranch
git stash pop

phpMyAdmin - The MySQL Extension is Missing

Just check your php.ini file, In this file Semicolon(;) used for comment if you see then remove semicolon ;.

;extension=mysql.dll

Now your extension is enable but you need to restart appache

extension=mysql.dll

fatal: 'origin' does not appear to be a git repository

It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)

git pull origin master

for me that simple call solved those error messages:

  • fatal: 'master' does not appear to be a git repository
  • fatal: Could not read from remote repository.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

If you're using jQuery 2.1.4 or above, try this:

$("#" + this.d);

Or, you can define var before using it. It makes your code simpler.

var d = this.d
$("#" + d);

Can I display the value of an enum with printf()?

enum A { foo, bar } a;
a = foo;
printf( "%d", a );   // see comments below

How to remove word wrap from textarea?

This question seems to be the most popular one for disabling textarea wrap. However, as of April 2017 I find that IE 11 (11.0.9600) will not disable word wrap with any of the above solutions.

The only solution which does work for IE 11 is wrap="off". wrap="soft" and/or the various CSS attributes like white-space: pre alter where IE 11 chooses to wrap but it still wraps somewhere. Note that I have tested this with or without Compatibility View. IE 11 is pretty HTML 5 compatible, but not in this case.

Thus, to achieve lines which retain their whitespace and go off the right-hand side I am using:

<textarea style="white-space: pre; overflow: scroll;" wrap="off">

Fortuitously this does seem to work in Chrome & Firefox too. I am not defending the use of pre-HTML 5 wrap="off", just saying that it seems to be required for IE 11.

Android camera intent

I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:

String fileloc;
private void openc()
{
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File f = null;
    try 
    {
        f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {               
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
            fileloc = Uri.fromFile(f)+"";
            Log.d("texts", "openc: "+fileloc);
            startActivityForResult(takePictureIntent, 3);
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 3 && resultCode == RESULT_OK) {
        Log.d("texts", "onActivityResult: "+fileloc);
        // fileloc is the uri of the file so do whatever with it
    }
}

You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."; 


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

execute function after complete page load

this may work for you :

document.addEventListener('DOMContentLoaded', function() {
   // your code here
}, false);

or if your comfort with jquery,

$(document).ready(function(){
// your code
});

$(document).ready() fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).

as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout function, before firing the function like below :

setTimeout(function(){
 //your code here
}, 3000);

What is the difference between explicit and implicit cursors in Oracle?

1.CURSOR: When PLSQL issues sql statements it creates private work area to parse & execute the sql statement is called cursor.

2.IMPLICIT: When any PL/SQLexecutable block issues sql statement. PL/SQL creates implicit cursor and manages automatically means implcit open & close takes place. It used when sql statement return only one row.It has 4 attributes SQL%ROWCOUNT, SQL%FOUND, SQL%NOTFOUND, SQL%ISOPEN.

3.EXPLICIT: It is created & managed by the programmer. It needs every time explicit open,fetch & close. It is used when sql statement returns more than one row. It has also 4 attributes CUR_NAME%ROWCOUNT, CUR_NAME%FOUND, CUR_NAME%NOTFOUND, CUR_NAME%ISOPEN. It process several rows by using loop. The programmer can pass the parameter too to explicit cursor.

  • Example: Explicit Cursor

 

declare 
   cursor emp_cursor 
   is 
   select id,name,salary,dept_id 
   from employees; 
   v_id employees.id%type; 
   v_name employees.name%type; 
   v_salary employees.salary%type; 
   v_dept_id employees.dept_id%type; 
   begin 
   open emp_cursor; 
   loop 
   fetch emp_cursor into v_id,v_name,v_salary,v_dept_id; 
   exit when emp_cursor%notfound;
   dbms_output.put_line(v_id||', '||v_name||', '||v_salary||','||v_dept_id); 
   end loop;                    
   close emp_cursor; 
   end;

Count character occurrences in a string in C++

There are several methods of std::string for searching, but find is probably what you're looking for. If you mean a C-style string, then the equivalent is strchr. However, in either case, you can also use a for loop and check each character—the loop is essentially what these two wrap up.

Once you know how to find the next character given a starting position, you continually advance your search (i.e. use a loop), counting as you go.

GCC dump preprocessor defines

While working in a big project which has complex build system and where it is hard to get (or modify) the gcc/g++ command directly there is another way to see the result of macro expansion. Simply redefine the macro, and you will get output similiar to following:

file.h: note: this is the location of the previous definition
#define MACRO current_value

Difference between __getattr__ vs __getattribute__

New-style classes inherit from object, or from another new style class:

class SomeObject(object):
    pass

class SubObject(SomeObject):
    pass

Old-style classes don't:

class SomeObject:
    pass

This only applies to Python 2 - in Python 3 all the above will create new-style classes.

See 9. Classes (Python tutorial), NewClassVsClassicClass and What is the difference between old style and new style classes in Python? for details.

Angular: conditional class with *ngClass

While I was creating a reactive form, I had to assign 2 types of class on the button. This is how I did it:

<button type="submit" class="btn" [ngClass]="(formGroup.valid)?'btn-info':''" 
[disabled]="!formGroup.valid">Sign in</button>

When the form is valid, button has btn and btn-class (from bootstrap), otherwise just btn class.

Facebook Access Token for Pages

  1. Go to the Graph API Explorer
  2. Choose your app from the dropdown menu
  3. Click "Get Access Token"
  4. Choose the manage_pages permission (you may need the user_events permission too, not sure)
  5. Now access the me/accounts connection and copy your page's access_token
  6. Click on your page's id
  7. Add the page's access_token to the GET fields
  8. Call the connection you want (e.g.: PAGE_ID/events)

How to debug in Android Studio using adb over WiFi

In Android Studio 3.0.1 > Goto > (Short cut key (Alt+Cltr+S)) Settings > Goto Plugins > Click on Browser repositories... > Search "ADB WIFI" and install the plugin. After the installation restart your android studio.

enter image description here

Click the icon enter image description here and connect your device.

Encrypt & Decrypt using PyCrypto AES 256

https://stackoverflow.com/a/21928790/11402877

compatible utf-8 encoding

def _pad(self, s):
    s = s.encode()
    res = s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs).encode()
    return res

What are good ways to prevent SQL injection?

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

HTML 5 video recording and storing a stream

RecordRTC: WebRTC audio/video recording

https://github.com/muaz-khan/WebRTC-Experiment/tree/master/RecordRTC

  • Audio recording both for Chrome and Firefox
  • Video/Gif recording for Chrome; (Firefox has a little bit issues, will be recovered soon)

Demo : https://www.webrtc-experiment.com/RecordRTC/


Creating .webm video from getUserMedia()

http://ericbidelman.tumblr.com/post/31486670538/creating-webm-video-from-getusermedia

Demo : http://html5-demos.appspot.com/static/getusermedia/record-user-webm.html


Capturing Audio & Video in HTML5

http://www.html5rocks.com/en/tutorials/getusermedia/intro/

Build and Install unsigned apk on device without the development server?

For Windows user if all steps followed properly from this: https://facebook.github.io/react-native/docs/signed-apk-android.html

You need to only run: gradlew assembleRelease

And your file will be:

  • app-release.apk
  • app-release-unaligned.apk

Location: E:\YourProjectName\android\app\build\outputs\apk

Does it matter what extension is used for SQLite database files?

In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db

The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!

Totally depends on your usage scenario I suppose.

How to get a list of installed Jenkins plugins with name and version pair

With curl and jq:

curl -s <jenkins_url>/pluginManager/api/json?depth=1 \
  | jq -r '.plugins[] | "\(.shortName):\(.version)"' \
  | sort

This command gives output in a format used by special Jenkins plugins.txt file which enables you to pre-install dependencies (e.g. in a docker image):

ace-editor:1.1
ant:1.8
apache-httpcomponents-client-4-api:4.5.5-3.0

Example of a plugins.txt: https://github.com/hoto/jenkinsfile-examples/blob/master/source/jenkins/usr/share/jenkins/plugins.txt

Hide/Show Action Bar Option Menu Item for different fragments

Try this

@Override
public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.custom_actionbar, menu);
    menu.setGroupVisible(...);
}

Getting around the Max String size in a vba function?

Excel only shows 255 characters but in fact if more than 255 characters are saved, to see the complete string, consult it in the immediate window

Press Crl + G and type ?RunWhat in the immediate window and press Enter

HTML Input Box - Disable

<input type="text" required="true" value="" readonly="true">

This will make a text box in readonly mode, might be helpful in generating passwords and datepickers.

How to compare only date components from DateTime in EF?

//Note for Linq Users/Coders

This should give you the exact comparison for checking if a date falls within range when working with input from a user - date picker for example:

((DateTime)ri.RequestX.DateSatisfied).Date >= startdate.Date &&
        ((DateTime)ri.RequestX.DateSatisfied).Date <= enddate.Date

where startdate and enddate are values from a date picker.

How can I dynamically add items to a Java array?

Use an ArrayList or juggle to arrays to auto increment the array size.

How to start up spring-boot application via command line?

One of the ways that you can run your spring-boot application from command line is as follows :

1) First go to your project directory in command line [where is your project located ?]

2) Then in the next step you have to create jar file for that, this can be done as

mvnw package [for WINDOWS OS ] or ./mvnw package [for MAC OS] , this will create jar file for our application.

3) jar file is created in the target sub-directory

4)Now go to target sub directory as jar was created inside of it , i.e cd target

5) Now run the jar file in there. Use command java -jar name.jar [ name is the name of your created jar file.]

and there you go , you are done . Now you can run project in browser,

 http://localhost:port_number

Select from where field not equal to Mysql Php

You can use also

select * from tablename where column1 ='a' and column2!='b';

            

Google Map API v3 — set bounds and center

My suggestion for google maps api v3 would be(don't think it can be done more effeciently):

gmap : {
    fitBounds: function(bounds, mapId)
    {
        //incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
        if (bounds==null) return false;
        maps[mapId].fitBounds(bounds);
    }
}

In the result u will fit all points in bounds in your map window.

Example works perfectly and u freely can check it here www.zemelapis.lt

Setting java locale settings

I believe java gleans this from the environment variables in which it was launched, so you'll need to make sure your LANG and LC_* environment variables are set appropriately.

The locale manpage has full info on said environment variables.

Django set field value after a form is initialized

in widget use 'value' attr. Example:

username = forms.CharField(
    required=False,
    widget=forms.TextInput(attrs={'readonly': True, 'value': 'CONSTANT_VALUE'}),
)

How can I tell which button was clicked in a PHP form submit?

All you need to give the name attribute to the each button. And you need to address each button press from the PHP script. But be careful to give each button a unique name. Because the PHP script only take care of the name most of the time

<input type="submit" name="Submit_this" id="This" />

Repair all tables in one go

No need to type in the password, just use any one of these commands (self explanatory):

mysqlcheck --all-databases -a #analyze
mysqlcheck --all-databases -r #repair
mysqlcheck --all-databases -o #optimize

Android: install .apk programmatically

For ICS I´ve implemented your code and made a class that extends AsyncTask. I hope you appreciate it! Thanks for your code and solution.

public class UpdateApp extends AsyncTask<String,Void,Void>{
    private Context context;
    public void setContext(Context contextf){
        context = contextf;
    }

    @Override
    protected Void doInBackground(String... arg0) {
        try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "update.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);


        } catch (Exception e) {
            Log.e("UpdateAPP", "Update error! " + e.getMessage());
        }
        return null;
    }
}   

To use it, in your main activity call by this way:

atualizaApp = new UpdateApp();
atualizaApp.setContext(getApplicationContext());
atualizaApp.execute("http://serverurl/appfile.apk");

How can I get column names from a table in SQL Server?

Summarizing the Answers

I can see many different answers and ways to do this but there is the rub in this and that is the objective.

Yes, the objective. If you want to only know the column names you can use

SELECT * FROM my_table WHERE 1=0
or
SELECT TOP 0 * FROM my_table

But if you want to use those columns somewhere or simply say manipulate them then the quick queries above are not going to be of any use. You need to use

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'Customers'

one more way to know some specific columns where we are in need of some similar columns

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME like N'%[ColumnName]%' and TABLE_NAME = N'[TableName]'

ipad safari: disable scrolling, and bounce effect?

You can also change the position of the body/html to fixed:

body,
html {
  position: fixed;
}