Programs & Examples On #Global asax

A special file in the ASP.NET framework, it provides a simplified interface to create hooks into system events in the life cycle of a web application and web pages in that application.

"Could not load type [Namespace].Global" causing me grief

go to configuration Manager under properties for your solution. Then make sure all projects and getting built, and this won't be a problem.

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

Multiple HttpPost method in Web API controller

I think the question has already been answered. I was also looking for something a webApi controller that has same signatured mehtods but different names. I was trying to implement the Calculator as WebApi. Calculator has 4 methods with the same signature but different names.

public class CalculatorController : ApiController
{
    [HttpGet]
    [ActionName("Add")]
    public string Add(int num1 = 1, int num2 = 1, int timeDelay = 1)
    {
        Thread.Sleep(1000 * timeDelay);
        return string.Format("Add = {0}", num1 + num2);
    }

    [HttpGet]
    [ActionName("Sub")]
    public string Sub(int num1 = 1, int num2 = 1, int timeDelay = 1)
    {
        Thread.Sleep(1000 * timeDelay);
        return string.Format("Subtract result = {0}", num1 - num2);
    }

    [HttpGet]
    [ActionName("Mul")]
    public string Mul(int num1 = 1, int num2 = 1, int timeDelay = 1)
    {
        Thread.Sleep(1000 * timeDelay);
        return string.Format("Multiplication result = {0}", num1 * num2);
    }

    [HttpGet]
    [ActionName("Div")]
    public string Div(int num1 = 1, int num2 = 1, int timeDelay = 1)
    {
        Thread.Sleep(1000 * timeDelay);
        return string.Format("Division result = {0}", num1 / num2);
    }
}

and in the WebApiConfig file you already have

 config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional });

Just set the authentication / authorisation on IIS and you are done!

Hope this helps!

PostgreSQL Exception Handling

Use the DO statement, a new option in version 9.0:

DO LANGUAGE plpgsql
$$
BEGIN
CREATE TABLE "Logs"."Events"
    (
        EventId BIGSERIAL NOT NULL PRIMARY KEY,
        PrimaryKeyId bigint NOT NULL,
        EventDateTime date NOT NULL DEFAULT(now()),
        Action varchar(12) NOT NULL,
        UserId integer NOT NULL REFERENCES "Office"."Users"(UserId),
        PrincipalUserId varchar(50) NOT NULL DEFAULT(user)
    );

    CREATE TABLE "Logs"."EventDetails"
    (
        EventDetailId BIGSERIAL NOT NULL PRIMARY KEY,
        EventId bigint NOT NULL REFERENCES "Logs"."Events"(EventId),
        Resource varchar(64) NOT NULL,
        OldVal varchar(4000) NOT NULL,
        NewVal varchar(4000) NOT NULL
    );

    RAISE NOTICE 'Task completed sucessfully.';    
END;
$$;

How to create web service (server & Client) in Visual Studio 2012?

  1. Create a new empty Asp.NET Web Application.
  2. Solution Explorer right click on the project root.
  3. Choose the menu item Add-> Web Service

How to restart service using command prompt?

To restart a running service:

net stop "service name" && net start "service name"

However, if you don't know if the service is running in the first place and want to restart or start it, use this:

net stop "service name" & net start "service name"

This works if the service is already running or not.

For reference, here is the documentation on conditional processing symbols.

str_replace with array

If the text is a simple markup and has existing anchors, stage the existing anchor tags first, swap out the urls, then replace the staged markers.

$text = '
Lorem Ipsum is simply dummy text found by searching http://google.com/?q=lorem in your <a href=https://www.mozilla.org/en-US/firefox/>Firefox</a>,
<a href="https://www.apple.com/safari/">Safari</a>, or https://www.google.com/chrome/ browser.

Link replacements will first stage existing anchor tags, replace each with a marker, then swap out the remaining links.
Links should be properly encoded.  If links are not separated from surrounding content like a trailing "." period then they it will be included in the link.
Links that are not encoded properly may create a problem, so best to use this when you know the text you are processing is not mixed HTML.

Example: http://google.com/i,m,complicate--d/index.html
Example: https://www.google.com/chrome/?123&t=123
Example: http://google.com/?q='. urlencode('<a href="http://google.com">http://google.com</a>') .'
';

// Replace existing links with a marker
$linkStore = array();
$text = preg_replace_callback('/(<a.*?a>)/', function($match) use (&$linkStore){ $key = '__linkStore'.count($linkStore).'__'; $linkStore[$key] = $match[0]; return $key; }, $text);

// Replace remaining URLs with an anchor tag
$text = preg_replace_callback("/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/", function($match) use (&$linkStore){ return '<a href="'. $match[0] .'">'. $match[0] .'</a>'; }, $text);

// Replace link markers with original
$text = str_replace(array_keys($linkStore), array_values($linkStore), $text);

echo '<pre>'.$text;

Delete with "Join" in Oracle sql Query

Based on the answer I linked to in my comment above, this should work:

delete from
(
select pf.* From PRODUCTFILTERS pf 
where pf.id>=200 
And pf.rowid in 
  (
     Select rowid from PRODUCTFILTERS 
     inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID 
     And PRODUCTS.NAME= 'Mark'
  )
); 

or

delete from PRODUCTFILTERS where rowid in
(
select pf.rowid From PRODUCTFILTERS pf 
where pf.id>=200 
And pf.rowid in 
  (
     Select PRODUCTFILTERS.rowid from PRODUCTFILTERS 
     inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID 
     And PRODUCTS.NAME= 'Mark'
  )
); 

Firefox Add-on RESTclient - How to input POST parameters?

If you want to submit a POST request

  1. You have to set the “request header” section of the Firefox plugin to have a “name” = “Content-Type” and “value” = “application/x-www-form-urlencoded
  2. Now, you are able to submit parameter like “name=mynamehere&title=TA” in the “request body” text area field

Conditional formatting using AND() function

COLUMN() and ROW() won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.

For instance, if you want to use this conditional formating on a range begining on cell A1, you can try:

`COLUMN(A1)` and `ROW(A1)`

Excel will automatically adapt the conditional formating to the current cell.

Best practice to run Linux service as a different user

On Debian we use the start-stop-daemon utility, which handles pid-files, changing the user, putting the daemon into background and much more.

I'm not familiar with RedHat, but the daemon utility that you are already using (which is defined in /etc/init.d/functions, btw.) is mentioned everywhere as the equivalent to start-stop-daemon, so either it can also change the uid of your program, or the way you do it is already the correct one.

If you look around the net, there are several ready-made wrappers that you can use. Some may even be already packaged in RedHat. Have a look at daemonize, for example.

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

I combined some of Flavio's answer to this small solution.

.hidden-ul-bullets li {
    list-style: none;
}
.hidden-ul-bullets ul {
    margin-left: 0.25em; // for my purpose, a little indentation is wished
}

The decision about bullets is made at an enclosing element, typically a div. The drawback (or todo) of my solution is that the liststyle removal also applies to ordered lists.

jQuery Datepicker with text input that doesn't allow user input

<input type="text" readonly="true" />

causes the textbox to lose its value after postback.

You rather should use Brad8118's suggestion which is working perfectly.

$("#my_txtbox").keypress(function(event) {event.preventDefault();});

EDIT: to get it working for IE use 'keydown' instead of 'keypress'

How to change the default encoding to UTF-8 for Apache?

<meta charset='utf-8'> overrides the apache default charset (cf /etc/apache2/conf.d/charset)

If this is not enough, then you probably created your original file with iso-8859-1 encoding character set. You have to convert it to the proper character set:

iconv -f ISO-8859-1 -t UTF-8 source_file.php -o new file.php

get launchable activity name of package from adb

$ adb shell pm dump PACKAGE_NAME | grep -A 1 MAIN

How to change button text in Swift Xcode 6?

swift 4 work as well as 3

libero.setTitle("---", for: .normal)

where libero is a uibutton

How can I hide or encrypt JavaScript code?

The only safe way to protect your code is not giving it away. With client deployment, there is no avoiding the client having access to the code.

So the short answer is: You can't do it

The longer answer is considering flash or Silverlight. Although I believe silverlight will gladly give away it's secrets with reflector running on the client.

I'm not sure if something simular exists with the flash platform.

javascript close current window

To close your current window using JS, do this. First open the current window to trick your current tab into thinking it has been opened by a script. Then close it using window.close(). The below script should go into the parent window, not the child window. You could run this after running the script to open the child.

<script type="text/javascript">
    window.open('','_parent',''); 
    window.close();
</script>

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

Mapping a JDBC ResultSet to an object

I would like to hint on q2o. It is a JPA based Java object mapper which helps with many of the tedious SQL and JDBC ResultSet related tasks, but without all the complexity an ORM framework comes with. With its help mapping a ResultSet to an object is as easy as this:

while(rs.next()) {
    users.add(Q2Obj.fromResultSet(rs, User.class));
}

More about q2o can be found here.

How to get access to HTTP header information in Spring MVC REST controller?

My solution in Header parameters with example is user="test" is:

@RequestMapping(value = "/restURL")
  public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){

System.out.println(headers.get("user"));
}

How to change default JRE for all Eclipse workspaces?

I have faced with the same issue. The resolve: - Window-->Preferences-->Java-->Installed JREs-->Add... - Right click on your project-->Build Path-->Configure Build Path-->Add library-->JRE system library-->next-->WorkSpace Default JRE

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

How can I run a directive after the dom has finished rendering?

If you can't use $timeout due to external resources and cant use a directive due to a specific issue with timing, use broadcast.

Add $scope.$broadcast("variable_name_here"); after the desired external resource or long running controller/directive has completed.

Then add the below after your external resource has loaded.

$scope.$on("variable_name_here", function(){ 
   // DOM manipulation here
   jQuery('selector').height(); 
}

For example in the promise of a deferred HTTP request.

MyHttpService.then(function(data){
   $scope.MyHttpReturnedImage = data.image;
   $scope.$broadcast("imageLoaded");
});

$scope.$on("imageLoaded", function(){ 
   jQuery('img').height(80).width(80); 
}

How to call an element in a numpy array?

Also, you could try to use ndarray.item(), for example, arr.item((0, 0))(rowid+colid to index) or arr.item(0)(flatten index), its doc https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html

jQuery get html of container including the container itself

var x = $('#container').get(0).outerHTML;

UPDATE : This is now supported by Firefox as of FireFox 11 (March 2012)

As others have pointed out, this will not work in FireFox. If you need it to work in FireFox, then you might want to take a look at the answer to this question : In jQuery, are there any function that similar to html() or text() but return the whole content of matched component?

How to get back to most recent version in Git?

To return to the latest version:

git checkout <branch-name> 

For example, git checkout master or git checkout dev

how to hide a vertical scroll bar when not needed

overflow: auto (or overflow-y: auto) is the correct way to go.

The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.

Try this: http://jsfiddle.net/G9rfq/1/

I set overflow:auto on the text box, and made the textbox the same size as the div.

Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen. Also your div isn't closed.

How to decode JWT Token?

I found the solution, I just forgot to Cast the result:

var stream ="[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;

I can get Claims using:

var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;

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

[INFO] BUILD SUCCESS
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
Anyway, it works for me:)

Output (echo/print) everything from a PHP Array

For nice & readable results, use this:

function printVar($var) {
    echo '<pre>';
    var_dump($var); 
    echo '</pre>';
}

The above function will preserve the original formatting, making it (more)readable in a web browser.

Integer division: How do you produce a double?

I don't like casting primitives, who knows what may happen.

Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int to a double. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int to double is a widening primitive conversion.

You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:

double d = num / (double) denom;

How do I launch a program from command line without opening a new cmd window?

1-Open you folder that contains your application in the File Explorer. 2-Press SHIFT and Right Click in White Space. 3-Click on "Open command window here". 4-Run your application. (you can type some of the first characters of application name and press Up Arrow Key OR Down Arrow Key)

Why is width: 100% not working on div {display: table-cell}?

Putting display:table; inside .outer-wrapper seemed to work...

JSFiddle Link


EDIT: Two Wrappers Using Display Table Cell

I would comment on your answer but i have too little rep :( anyways...

Going off your answer, seems like all you need to do is add display:table; inside .outer-wrapper (Dejavu?), and you can get rid of table-wrapper whole-heartedly.

JSFiddle

But yeah, the position:absolute lets you place the div over the img, I read too quickly and thought that you couldn't use position:absolute at all, but seems like you figured it out already. Props!

I'm not going to post the source code, after all its 99% timshutes's work, so please refer to his answer, or just use my jsfiddle link

Update: One Wrapper Using Flexbox

It's been a while, and all the cool kids are using flexbox:

<div style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
    stuff to be centered
</div>

Full JSFiddle Solution

Browser Support (source): IE 11+, FireFox 42+, Chrome 46+, Safari 8+, iOS 8.4+ (-webkit- prefix), Android 4.1+ (-webkit- prefix)

CSS Tricks: a Guide to Flexbox

How to Center in CSS: input how you want your content to be centered, and it outputs how to do it in html and css. The future is here!

Create a dropdown component

This might not exactly you want but I've used jquery smartmenu(https://github.com/vadikom/smartmenus) to build a ng2 dropdown menu.

 $('#main-menu').smartmenus();

http://plnkr.co/edit/wLqLUoBQYgcDwOgSoRfF?p=preview https://github.com/Longfld/DynamicaLoadMultiLevelDropDownMenu

C++ "was not declared in this scope" compile error

The first argument to nonrecursivecountcells() doesn't have a variable name. You try to reference it as grid in the function body, so you probably want to call it grid.

How can I trigger a JavaScript event click

.click() does not work with Android (look at mozilla docs, at mobile section). You can trigger the click event with this method:

function fireClick(node){
    if (document.createEvent) {
        var evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, false);
        node.dispatchEvent(evt);    
    } else if (document.createEventObject) {
        node.fireEvent('onclick') ; 
    } else if (typeof node.onclick == 'function') {
        node.onclick(); 
    }
}

From this post

What is a good way to handle exceptions when trying to read a file in python?

Here is a read/write example. The with statements insure the close() statement will be called by the file object regardless of whether an exception is thrown. http://effbot.org/zone/python-with-statement.htm

import sys

fIn = 'symbolsIn.csv'
fOut = 'symbolsOut.csv'

try:
   with open(fIn, 'r') as f:
      file_content = f.read()
      print "read file " + fIn
   if not file_content:
      print "no data in file " + fIn
      file_content = "name,phone,address\n"
   with open(fOut, 'w') as dest:
      dest.write(file_content)
      print "wrote file " + fOut
except IOError as e:
   print "I/O error({0}): {1}".format(e.errno, e.strerror)
except: #handle other exceptions such as attribute errors
   print "Unexpected error:", sys.exc_info()[0]
print "done"

How do I test if a string is empty in Objective-C?

//Different validations:
 NSString * inputStr = @"Hey ";

//Check length
[inputStr length]

//Coming from server, check if its NSNull
[inputStr isEqual:[NSNull null]] ? nil : inputStr

//For validation in allowed character set
-(BOOL)validateString:(NSString*)inputStr
{
    BOOL isValid = NO;
    if(!([inputStr length]>0))
    {
        return isValid;

    }

    NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@".-"];
    [allowedSet formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
    if ([inputStr rangeOfCharacterFromSet:[allowedSet invertedSet]].location == NSNotFound)
    {
        // contains only decimal set and '-' and '.'

    }
    else
    {
        // invalid
        isValid = NO;

    }
    return isValid;
}

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Interface means a class that has no implementation of its method, but with just declaration.
Other hand, abstract class is a class that can have implementation of some method along with some method with just declaration, no implementation.
When we implement an interface to an abstract class, its means that the abstract class inherited all the methods of the interface. As, it is not important to implement all the method in abstract class however it comes to abstract class (by inheritance too), so the abstract class can left some of the method in interface without implementation here. But, when this abstract class will inherited by some concrete class, they must have to implements all those unimplemented method there in abstract class.

I need to get all the cookies from the browser

You can only access cookies for a specific site. Using document.cookie you will get a list of escaped key=value pairs seperated by a semicolon.

secret=do%20not%20tell%you;last_visit=1225445171794

To simplify the access, you have to parse the string and unescape all entries:

var getCookies = function(){
  var pairs = document.cookie.split(";");
  var cookies = {};
  for (var i=0; i<pairs.length; i++){
    var pair = pairs[i].split("=");
    cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
  }
  return cookies;
}

So you might later write:

var myCookies = getCookies();
alert(myCookies.secret); // "do not tell you"

Is there a way that I can check if a data attribute exists?

Wrong answer - see EDIT at the end

Let me build on Alex's answer.

To prevent the creation of a data object if it doesn't exists, I would better do:

$.fn.hasData = function(key) {
    var $this = $(this);
    return $.hasData($this) && typeof $this.data(key) !== 'undefined';
};

Then, where $this has no data object created, $.hasData returns false and it will not execute $this.data(key).

EDIT: function $.hasData(element) works only if the data was set using $.data(element, key, value), not element.data(key, value). Due to that, my answer is not correct.

How to do a scatter plot with empty circles in Python?

In matplotlib 2.0 there is a parameter called fillstyle which allows better control on the way markers are filled. In my case I have used it with errorbars but it works for markers in general http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html

fillstyle accepts the following values: [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]

There are two important things to keep in mind when using fillstyle,

1) If mfc is set to any kind of value it will take priority, hence, if you did set fillstyle to 'none' it would not take effect. So avoid using mfc in conjuntion with fillstyle

2) You might want to control the marker edge width (using markeredgewidth or mew) because if the marker is relatively small and the edge width is thick, the markers will look like filled even though they are not.

Following is an example using errorbars:

myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue',  mec='blue')

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    margin:10px;
    float:left;/*Add float left*/
    margin :10px;
}

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.

fiddle

What is the difference between RTP or RTSP in a streaming server?

AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.

Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.

To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.

Pretty much everything can be transported through TCP though.

(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

How do I fix the multiple-step OLE DB operation errors in SSIS?

This issue will come mostly due to empty rows at the end of the file, remove those and run the job.

Scrolling to an Anchor using Transition/CSS3

I guess it might be possible to set some kind of hardcore transition to the top style of a #container div to move your entire page in the desired direction when clicking your anchor. Something like adding a class that has top:-2000px.

I did use JQuery because I'm to lazy too use native JS, but it is not necessary for what I did.

This is probably not the best possible solution because the top content just moves towards the top and you can't get it back easily, you should definitely use JQuery if you really need that scroll animation.

DEMO

How to do multiple arguments to map function where one remains the same in python?

Use a list comprehension.

[x + 2 for x in [1, 2, 3]]

If you really, really, really want to use map, give it an anonymous function as the first argument:

map(lambda x: x + 2, [1,2,3])

How to show shadow around the linearlayout in Android?

  1. save this 9.png. (change name it to 9.png)

enter image description here

2.save it in your drawable.

3.set it to your layout.

4.set padding.

For example :

<LinearLayout  
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/shadow"
  android:paddingBottom="6dp"
  android:paddingLeft="5dp"
  android:paddingRight="5dp"
  android:paddingTop="6dp"
>

.
.
.
</LinearLayout>

Difference between 'struct' and 'typedef struct' in C++?

There is a difference, but subtle. Look at it this way: struct Foo introduces a new type. The second one creates an alias called Foo (and not a new type) for an unnamed struct type.

7.1.3 The typedef specifier

1 [...]

A name declared with the typedef specifier becomes a typedef-name. Within the scope of its declaration, a typedef-name is syntactically equivalent to a keyword and names the type associated with the identifier in the way described in Clause 8. A typedef-name is thus a synonym for another type. A typedef-name does not introduce a new type the way a class declaration (9.1) or enum declaration does.

8 If the typedef declaration defines an unnamed class (or enum), the first typedef-name declared by the declaration to be that class type (or enum type) is used to denote the class type (or enum type) for linkage purposes only (3.5). [ Example:

typedef struct { } *ps, S; // S is the class name for linkage purposes

So, a typedef always is used as an placeholder/synonym for another type.

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

SELECT * 
FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time

Or,

SELECT * 
FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

How to define optional methods in Swift protocol?

  • You need to add optional keyword prior to each method.
  • Please note, however, that for this to work, your protocol must be marked with the @objc attribute.
  • This further implies that this protocol would be applicable to classes but not structures.

How to determine MIME type of file in android?

Sometimes Jeb's and Jens's answers don't work and return null. In this case I use follow solution. Head of file usually contains type signature. I read it and compare with known in list of signatures.

/**
 *
 * @param is InputStream on start of file. Otherwise signature can not be defined.
 * @return int id of signature or -1, if unknown signature was found. See SIGNATURE_ID_(type) constants to
 *      identify signature by its id.
 * @throws IOException in cases of read errors.
 */
public static int getSignatureIdFromHeader(InputStream is) throws IOException {
    // read signature from head of source and compare with known signatures
    int signatureId = -1;
    int sigCount = SIGNATURES.length;
    int[] byteArray = new int[MAX_SIGNATURE_LENGTH];
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {
        byteArray[i] = is.read();
        builder.append(Integer.toHexString(byteArray[i]));
    }
    if (DEBUG) {
        Log.d(TAG, "head bytes=" + builder.toString());
    }
    for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {

        // check each bytes with known signatures
        int bytes = byteArray[i];
        int lastSigId = -1;
        int coincidences = 0;

        for (int j = 0; j < sigCount; j++) {
            int[] sig = SIGNATURES[j];

            if (DEBUG) {
                Log.d(TAG, "compare" + i + ": " + Integer.toHexString(bytes) + " with " + sig[i]);
            }
            if (bytes == sig[i]) {
                lastSigId = j;
                coincidences++;
            }
        }

        // signature is unknown
        if (coincidences == 0) {
            break;
        }
        // if first bytes of signature is known we check signature for full coincidence
        if (coincidences == 1) {
            int[] sig = SIGNATURES[lastSigId];
            int sigLength = sig.length;
            boolean isSigKnown = true;
            for (; i < MAX_SIGNATURE_LENGTH && i < sigLength; i++) {
                bytes = byteArray[i];
                if (bytes != sig[i]) {
                    isSigKnown = false;
                    break;
                }
            }
            if (isSigKnown) {
                signatureId = lastSigId;
            }
            break;
        }
    }
    return signatureId;
}

signatureId is an index of signature in array of signatures. For example,

private static final int[] SIGNATURE_PNG = hexStringToIntArray("89504E470D0A1A0A");
private static final int[] SIGNATURE_JPEG = hexStringToIntArray("FFD8FF");
private static final int[] SIGNATURE_GIF = hexStringToIntArray("474946");

public static final int SIGNATURE_ID_JPEG = 0;
public static final int SIGNATURE_ID_PNG = 1;
public static final int SIGNATURE_ID_GIF = 2;
private static final int[][] SIGNATURES = new int[3][];

static {
    SIGNATURES[SIGNATURE_ID_JPEG] = SIGNATURE_JPEG;
    SIGNATURES[SIGNATURE_ID_PNG] = SIGNATURE_PNG;
    SIGNATURES[SIGNATURE_ID_GIF] = SIGNATURE_GIF;
}

Now I have file type even if URI of file haven't. Next I get mime type by file type. If you don't know which mime type to get, you can find proper in this table.

It works for a lot of file types. But for video it doesn't work, because you need to known video codec to get a mime type. To get video's mime type I use MediaMetadataRetriever.

format a number with commas and decimals in C# (asp.net MVC3)

Your question is not very clear but this should achieve what you are trying to do:

decimal numericValue = 3494309432324.00m;
string formatted = numericValue.ToString("#,##0.00");

Then formatted will contain: 3,494,309,432,324.00

What is the easiest way to parse an INI File in C++?

If you are interested in platform portability, you can also try Boost.PropertyTree. It supports ini as persistancy format, though the property tree my be 1 level deep only.

java.lang.RuntimeException: Unable to start activity ComponentInfo

It was my own stupidity:

java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());

Putting this inside onCreate() method fixed my problem.

Execution failed for task ':app:compileDebugAidl': aidl is missing

Essentially Matt Daley/Johnny Mohseni's solution worked for me.

I faced exactly the same problem on a fresh Android Studio V 1.2.1.1 installation. I created a new project (blank activity) and straightaway god this build error.

Error:Execution failed for task ':app:compileDebugAidl'.
> aidl is missing

As suggested, changing the gradle dependency from 1.2.3 to 1.3.0-beta1 fixed it.

classpath 'com.android.tools.build:gradle:1.3.0-beta1' // <--- WORKS! 
//classpath 'com.android.tools.build:gradle:1.2.3' // <--- default - failed

Once 1.3.0-beta1 change was saved, I got a prompt to upgrade dependencies. Upon accepting the request to upgrade, the gradle build status bar at the bottom tracked the packages being synced. When that completed, the build was automatically triggered and completed successfully.

Click event doesn't work on dynamically generated elements

Use 'on' as click gets bind to the elements already present.

For e.g

$('test').on('click',function(){
    alert('Test');
})

This will help.

How to run multiple SQL commands in a single SQL connection?

Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection

public static class SQLTest
    {
        public static void NpgsqlCommand()
        {
            using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
            {
                NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
                NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
                command1.Connection.Open();
                command1.ExecuteNonQuery();
                command2.ExecuteNonQuery();
                command2.Connection.Close();
            }
        }
    }

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

A trick I haven't seen on here yet that doesn't use extglob, find, or grep is to treat two file lists as sets and "diff" them using comm:

comm -23 <(ls) <(ls *Music*)

comm is preferable over diff because it doesn't have extra cruft.

This returns all elements of set 1, ls, that are not also in set 2, ls *Music*. This requires both sets to be in sorted order to work properly. No problem for ls and glob expansion, but if you're using something like find, be sure to invoke sort.

comm -23 <(find . | sort) <(find . | grep -i '.jpg' | sort)

Potentially useful.

Just get column names from hive table

use desc tablename from Hive CLI or beeline to get all the column names. If you want the column names in a file then run the below command from the shell.

$ hive -e 'desc dbname.tablename;' > ~/columnnames.txt

where dbname is the name of the Hive database where your table is residing You can find the file columnnames.txt in your root directory.

$cd ~
$ls

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.

Map:

class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};
    }

    add(key: string, value: T): void {
        this.items[key] = value;
    }

    has(key: string): boolean {
        return key in this.items;
    }

    get(key: string): T {
        return this.items[key];
    }
}

List:

class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(value);
    }

    get(index: number): T {
        return this.items[index];
    }
}

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;
    }

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);
    }

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   
    }
}

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));
    }

    get(index: number): ListItem<T> {
        return this.items[index];
    }
}

Here too you're looking at untested code..

Hope this helps.


Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1

Regex Until But Not Including

A lookahead regex syntax can help you to achieve your goal. Thus a regex for your example is

.*?quick.*?(?=z)

And it's important to notice the .*? lazy matching before the (?=z) lookahead: the expression matches a substring until a first occurrence of the z letter.

Here is C# code sample:

const string text = "The quick red fox jumped over the lazy brown dogz";

string lazy = new Regex(".*?quick.*?(?=z)").Match(text).Value;
Console.WriteLine(lazy); // The quick red fox jumped over the la

string greedy = new Regex(".*?quick.*(?=z)").Match(text).Value;
Console.WriteLine(greedy); // The quick red fox jumped over the lazy brown dog

Recommended SQL database design for tags or tagging

If you are using a database that supports map-reduce, like couchdb, storing tags in a plain text field or list field is indeed the best way. Example:

tagcloud: {
  map: function(doc){ 
    for(tag in doc.tags){ 
      emit(doc.tags[tag],1) 
    }
  }
  reduce: function(keys,values){
    return values.length
  }
}

Running this with group=true will group the results by tag name, and even return a count of the number of times that tag was encountered. It's very similar to counting the occurrences of a word in text.

Make a borderless form movable?

Also if you need to DoubleClick and make your Form bigger/smaller , you can use the First answer, create a global int variable, add 1 every time user clicks on the component you use for dragging. If variable == 2 then make your form bigger/smaller. Also use a timer for every half a sec or a second to make your variable = 0;

"Couldn't read dependencies" error with npm


Problem with not reading the json is linked to permission issues with the file.

Using this command will do the trick:

sudo chown -R $USER:$GROUP ~/.npm

How do I convert an interval into a number of hours with postgres?

If you want integer i.e. number of days:

SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int

Twitter Bootstrap 3: how to use media queries?

you can see in my example font sizes and background colors are changing according to the screen size

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<style>_x000D_
body {_x000D_
    background-color: lightgreen;_x000D_
}_x000D_
/* Custom, iPhone Retina */ _x000D_
@media(max-width:320px){_x000D_
    body {_x000D_
        background-color: lime;_x000D_
        font-size:14px;_x000D_
     }_x000D_
}_x000D_
@media only screen and (min-width : 320px) {_x000D_
     body {_x000D_
        background-color: red;_x000D_
        font-size:18px;_x000D_
    }_x000D_
}_x000D_
/* Extra Small Devices, Phones */ _x000D_
@media only screen and (min-width : 480px) {_x000D_
     body {_x000D_
        background-color: aqua;_x000D_
        font-size:24px;_x000D_
    }_x000D_
}_x000D_
/* Small Devices, Tablets */_x000D_
@media only screen and (min-width : 768px) {_x000D_
     body {_x000D_
        background-color: green;_x000D_
        font-size:30px;_x000D_
    }_x000D_
}_x000D_
/* Medium Devices, Desktops */_x000D_
@media only screen and (min-width : 992px) {_x000D_
     body {_x000D_
        background-color: grey;_x000D_
        font-size:34px;_x000D_
    }_x000D_
}_x000D_
/* Large Devices, Wide Screens */_x000D_
@media only screen and (min-width : 1200px) {_x000D_
     body {_x000D_
        background-color: black;_x000D_
        font-size:42px;_x000D_
    }_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<p>Resize the browser window. When the width of this document is larger than the height, the background-color is "lightblue", otherwise it is "lightgreen".</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I simulate placeholder functionality on input date field?

use this input attribute events

onfocus="(this.type='date')" onblur="(this.type='text')"

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
<div class="container mt-3">_x000D_
  <label for="date">Date : </label>_x000D_
  <input placeholder="Your Date" class="form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if pytorch is using the GPU?

This is going to work :

In [1]: import torch

In [2]: torch.cuda.current_device()
Out[2]: 0

In [3]: torch.cuda.device(0)
Out[3]: <torch.cuda.device at 0x7efce0b03be0>

In [4]: torch.cuda.device_count()
Out[4]: 1

In [5]: torch.cuda.get_device_name(0)
Out[5]: 'GeForce GTX 950M'

In [6]: torch.cuda.is_available()
Out[6]: True

This tells me the GPU GeForce GTX 950M is being used by PyTorch.

Difference between break and continue in PHP?

For the Record:

Note that in PHP the switch statement is considered a looping structure for the purposes of continue.

How do you do block comments in YAML?

One way to block commenting in YAML is by using a text editor like Notepad++ to add a # (comment) tag to multiple lines at once.

In Notepad++ you can do that using the "Block Comment" right-click option for selected text.

Woo Images!

Converting integer to string in Python

You can use %s or .format:

>>> "%s" % 10
'10'
>>>

Or:

>>> '{}'.format(10)
'10'
>>>

what is the difference between ajax and jquery and which one is better?

It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.

It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

IOException: The process cannot access the file 'file path' because it is being used by another process

I had the following scenario that was causing the same error:

  • Upload files to the server
  • Then get rid of the old files after they have been uploaded

Most files were small in size, however, a few were large, and so attempting to delete those resulted in the cannot access file error.

It was not easy to find, however, the solution was as simple as Waiting "for the task to complete execution":

using (var wc = new WebClient())
{
   var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
   tskResult.Wait(); 
}

file_put_contents(meta/services.json): failed to open stream: Permission denied

Setting permission to 777 is definitely terrible idea!

... but

If you are getting permission error connected with "storage" folder that's what worked for me:

1) Set "storage" and its subfolders permission to 777 with

sudo chmod -R 777 storage/

2) In browser go to laravel home page laravel/public/ (laravel will create necessary initial storage files)

3) Return safe 775 permission to storage and its subfolders

sudo chmod -R 775 storage/

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

Historically, the first extensions used for C++ were .c and .h, exactly like for C. This caused practical problems, especially the .c which didn't allow build systems to easily differentiate C++ and C files.

Unix, on which C++ has been developed, has case sensitive file systems. So some used .C for C++ files. Other used .c++, .cc and .cxx. .C and .c++ have the problem that they aren't available on other file systems and their use quickly dropped. DOS and Windows C++ compilers tended to use .cpp, and some of them make the choice difficult, if not impossible, to configure. Portability consideration made that choice the most common, even outside MS-Windows.

Headers have used the corresponding .H, .h++, .hh, .hxx and .hpp. But unlike the main files, .h remains to this day a popular choice for C++ even with the disadvantage that it doesn't allow to know if the header can be included in C context or not. Standard headers now have no extension at all.

Additionally, some are using .ii, .ixx, .ipp, .inl for headers providing inline definitions and .txx, .tpp and .tpl for template definitions. Those are either included in the headers providing the definition, or manually in the contexts where they are needed.

Compilers and tools usually don't care about what extensions are used, but using an extension that they associate with C++ prevents the need to track out how to configure them so they correctly recognize the language used.

2017 edit: the experimental module support of Visual Studio recognize .ixx as a default extension for module interfaces, clang++ is recognizing .c++m, .cppm and .cxxm for the same purpose.

XML Carriage return encoding

To insert a CR into XML, you need to use its character entity &#13;.

This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.

Pandas DataFrame to List of Dictionaries

If you are interested in only selecting one column this will work.

df[["item1"]].to_dict("records")

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

df["item1"].to_dict("records")

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

Get all table names of a particular database by SQL query?

USE dbName;

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_SCHEMA = 'dbName' OR TABLE_SCHEMA = 'schemaName')
ORDER BY TABLE_NAME

If you are working with multiple schemata on an MS SQL server, then SELECT-ing TABLE_NAME without also simultaneously selecting TABLE_SCHEMA might be of limited benefit, so I have assumed we are interested in the tables belonging to a known schema when using MS SQL Server.

I have tested the query above with SQL Server Management Studio using an SQL Server database of mine and with MySQL Workbench using a MySQL database, and in both cases it gives the table names.

The query bodges Michael Baylon's two different queries into one that can then run on either database type. The first part of the WHERE clause works on MySQL databases and the second part (after the OR) works on MS SQL Server databases. It is ugly and logically a little incorrect as it supposes that there is no undesired schema with the same name as the database. This might help someone who is looking for one single query that can run on either database server.

Equivalent function for DATEADD() in Oracle

Method1: ADD_MONTHS

ADD_MONTHS(SYSDATE, -6)

Method 2: Interval

SYSDATE - interval '6' month

Note: if you want to do the operations from start of the current month always, TRUNC(SYSDATE,'MONTH') would give that. And it expects a Date datatype as input.

Maven error :Perhaps you are running on a JRE rather than a JDK?

Check if /usr/bin has 'javac'. If not you have installed JRE & have to install jdk dev version like "java-1.8.0-openjdk-devel.x86_64"

CodeIgniter 404 Page Not Found, but why?

Your folder/file structure seems a little odd to me. I can't quite figure out how you've got this laid out.

Hello I am using CodeIgniter for two applications (a public and an admin app).

This sounds to me like you've got two separate CI installations. If this is the case, I'd recommend against it. Why not just handle all admin stuff in an admin controller? If you do want two separate CI installations, make sure they are definitely distinct entities and that the two aren't conflicting with one another. This line:

$system_folder = "../system";
$application_folder = "../application/admin"; (this line exists of course twice)

And the place you said this exists (/admin/index.php...or did you mean /admin/application/config?) has me scratching my head. You have admin/application/admin and a system folder at the top level?

What is the difference between linear regression and logistic regression?

In case of Linear Regression the outcome is continuous while in case of Logistic Regression outcome is discrete (not continuous)

To perform Linear regression we require a linear relationship between the dependent and independent variables. But to perform Logistic regression we do not require a linear relationship between the dependent and independent variables.

Linear Regression is all about fitting a straight line in the data while Logistic Regression is about fitting a curve to the data.

Linear Regression is a regression algorithm for Machine Learning while Logistic Regression is a classification Algorithm for machine learning.

Linear regression assumes gaussian (or normal) distribution of dependent variable. Logistic regression assumes binomial distribution of dependent variable.

Spring Boot Configure and Use Two DataSources

My requirement was slightly different but used two data sources.

I have used two data sources for same JPA entities from same package. One for executing DDL at the server startup to create/update tables and another one is for DML at runtime.

The DDL connection should be closed after DDL statements are executed, to prevent further usage of super user previlleges anywhere in the code.

Properties

spring.datasource.url=jdbc:postgresql://Host:port
ddl.user=ddluser
ddl.password=ddlpassword
dml.user=dmluser
dml.password=dmlpassword
spring.datasource.driver-class-name=org.postgresql.Driver

Data source config classes

//1st Config class for DDL Data source

  public class DatabaseDDLConfig {
        @Bean
        public LocalContainerEntityManagerFactoryBean ddlEntityManagerFactoryBean() {
            LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
            PersistenceProvider persistenceProvider = new 
            org.hibernate.jpa.HibernatePersistenceProvider();
            entityManagerFactoryBean.setDataSource(ddlDataSource());
            entityManagerFactoryBean.setPackagesToScan(new String[] { 
            "com.test.two.data.sources"});
            HibernateJpaVendorAdapter vendorAdapter = new 
            HibernateJpaVendorAdapter();
            entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
            HashMap<String, Object> properties = new HashMap<>();
            properties.put("hibernate.dialect", 
            "org.hibernate.dialect.PostgreSQLDialect");
            properties.put("hibernate.physical_naming_strategy", 
            "org.springframework.boot.orm.jpa.hibernate.
            SpringPhysicalNamingStrategy");
            properties.put("hibernate.implicit_naming_strategy", 
            "org.springframework.boot.orm.jpa.hibernate.
            SpringImplicitNamingStrategy");
            properties.put("hibernate.hbm2ddl.auto", "update");
            entityManagerFactoryBean.setJpaPropertyMap(properties);
            entityManagerFactoryBean.setPersistenceUnitName("ddl.config");
            entityManagerFactoryBean.setPersistenceProvider(persistenceProvider);
            return entityManagerFactoryBean;
        }


    @Bean
    public DataSource ddlDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("ddl.user");
        dataSource.setPassword(env.getProperty("ddl.password"));
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager ddlTransactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(ddlEntityManagerFactoryBean().getObject());
        return transactionManager;
    }
}

//2nd Config class for DML Data source

public class DatabaseDMLConfig {

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean dmlEntityManagerFactoryBean() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        PersistenceProvider persistenceProvider = new org.hibernate.jpa.HibernatePersistenceProvider();
        entityManagerFactoryBean.setDataSource(dmlDataSource());
        entityManagerFactoryBean.setPackagesToScan(new String[] { "com.test.two.data.sources" });
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
        entityManagerFactoryBean.setJpaProperties(defineJpaProperties());
        entityManagerFactoryBean.setPersistenceUnitName("dml.config");
        entityManagerFactoryBean.setPersistenceProvider(persistenceProvider);
        return entityManagerFactoryBean;
    }

    @Bean
    @Primary
    public DataSource dmlDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(envt.getProperty("spring.datasource.url"));
        dataSource.setUsername("dml.user");
        dataSource.setPassword("dml.password");
        return dataSource;
    }

    @Bean
    @Primary
    public PlatformTransactionManager dmlTransactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(dmlEntityManagerFactoryBean().getObject());
        return transactionManager;
    }


  }

//Usage of DDL data sources in code.

public class DDLServiceAtStartup {

//Import persistence unit ddl.config for ddl purpose.

@PersistenceUnit(unitName = "ddl.config")
private EntityManagerFactory entityManagerFactory;

public void executeDDLQueries() throws ContentServiceSystemError {
    try {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.createNativeQuery("query to create/update table").executeUpdate();
        entityManager.flush();
        entityManager.getTransaction().commit();
        entityManager.close();

        //Close the ddl data source to avoid from further use in code.
        entityManagerFactory.close();
    } catch(Exception ex) {}
}

//Usage of DML data source in code.

public class DDLServiceAtStartup {
  @PersistenceUnit(unitName = "dml.config")
  private EntityManagerFactory entityManagerFactory;

  public void createRecord(User user) {
     userDao.save(user);
  }
}

How can I create a table with borders in Android?

My solution for this problem is to put an xml drawable resource on the background field of every cell. In this manner you could define a shape with the border you want for all cells. The only inconvenience is that the borders of the extreme cells have half the width of the others but it's no problem if your table fills the entire screen.

An Example:

drawable/cell_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape= "rectangle"  >
        <solid android:color="#000"/>
        <stroke android:width="1dp"  android:color="#ff9"/>
</shape>

layout/my_table.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TableRow
        android:id="@+id/tabla_cabecera"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></TableRow>

    <TableLayout
        android:id="@+id/tabla_cuerpo"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>
    </TableLayout>


</LinearLayout>

Edit: An example

enter image description here

Edit2: Another example (with more elements: circle corners, gradients...) enter image description here

I have explained this issue with more details in http://blog.intelligenia.com/2012/02/programacion-movil-en-android.html#more. It's in spanish but there are some codes and images of more complex tables.

Add legend to ggplot2 line plot

I tend to find that if I'm specifying individual colours in multiple geom's, I'm doing it wrong. Here's how I would plot your data:

##Subset the necessary columns
dd_sub = datos[,c(20, 2,3,5)]
##Then rearrange your data frame
library(reshape2)
dd = melt(dd_sub, id=c("fecha"))

All that's left is a simple ggplot command:

ggplot(dd) + geom_line(aes(x=fecha, y=value, colour=variable)) +
  scale_colour_manual(values=c("red","green","blue"))

Example plot

enter image description here

How to get main window handle from process id?

Though it may be unrelated to your question, take a look at GetGUIThreadInfo Function.

Jackson JSON custom serialization for certain fields

You can implement a custom serializer as follows:

public class Person {
    public String name;
    public int age;
    @JsonSerialize(using = IntToStringSerializer.class, as=String.class)
    public int favoriteNumber:
}


public class IntToStringSerializer extends JsonSerializer<Integer> {

    @Override
    public void serialize(Integer tmpInt, 
                          JsonGenerator jsonGenerator, 
                          SerializerProvider serializerProvider) 
                          throws IOException, JsonProcessingException {
        jsonGenerator.writeObject(tmpInt.toString());
    }
}

Java should handle the autoboxing from int to Integer for you.

How to extract IP Address in Spring MVC Controller get call?

private static final String[] IP_HEADER_CANDIDATES = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR"
    };

    public static String getIPFromRequest(HttpServletRequest request) {
        String ip = null;
        if (request == null) {
            if (RequestContextHolder.getRequestAttributes() == null) {
                return null;
            }
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }

        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!StringUtils.isEmpty(ip))
            return ip;

        for (String header : IP_HEADER_CANDIDATES) {
            String ipList = request.getHeader(header);
            if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
                return ipList.split(",")[0];
            }
        }

        return request.getRemoteAddr();
    }

I combie the code above to this code work for most case. Pass the HttpServletRequest request you get from the api to the method

What exactly is std::atomic?

I understand that std::atomic<> makes an object atomic.

That's a matter of perspective... you can't apply it to arbitrary objects and have their operations become atomic, but the provided specialisations for (most) integral types and pointers can be used.

a = a + 12;

std::atomic<> does not (use template expressions to) simplify this to a single atomic operation, instead the operator T() const volatile noexcept member does an atomic load() of a, then twelve is added, and operator=(T t) noexcept does a store(t).

Link to a section of a webpage

Simple:

Use <section>.

and use <a href="page.html#tips">Visit the Useful Tips Section</a>

w3school.com/html_links

How to define Gradle's home in IDEA?

C:\Users\<_username>\.gradle\wrapper\dists\gradle-<_version>-all\<_number_random_maybe>\gradle-<_version>

\Android studio\gradle didn't worked for me.

And "Default gradle wrapper" wasn't configured while importing (cloning) the project from bitbucket

If it causes problem to figure out the path, here is my path :

C:\Users\prabs\.gradle\wrapper\dists\gradle-5.4.1-all\3221gyojl5jsh0helicew7rwx\gradle-5.4.1

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

Use this

After setup this you will not receive this issue again

SET PASSWORD FOR root@localhost = PASSWORD('your_root_password');

I was stuck up in this issue after used this query everything was solved

How to hide a button programmatically?

Please try this: playButton = (Button) findViewById(R.id.play); playButton.setVisibility(View.INVISIBLE); I think this will do it.

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

I am not sure and not really trust $_SERVER['HTTP_HOST'] because it depend on header from client. In another way, if a domain requested by client is not mine one, they will not getting into my site because DNS and TCP/IP protocol point it to the correct destination. However I don't know if possible to hijack the DNS, network or even Apache server. To be safe, I define host name in environment and compare it with $_SERVER['HTTP_HOST'].

Add SetEnv MyHost domain.com in .htaccess file on root and add ths code in Common.php

if (getenv('MyHost')!=$_SERVER['HTTP_HOST']) {
  header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
  exit();
}

I include this Common.php file in every php page. This page doing anything required for each request like session_start(), modify session cookie and reject if post method come from different domain.

Returning Month Name in SQL Server Query

This will give you the full name of the month.

select datename(month, S0.OrderDateTime)

If you only want the first three letters you can use this

select convert(char(3), S0.OrderDateTime, 0)

Can an Option in a Select tag carry multiple values?

What about html data attributes? That's the easiest way. Reference from w3school

In your case

_x000D_
_x000D_
$('select').on('change', function() {_x000D_
  alert('value a is:' + $("select option:selected").data('valuea') +_x000D_
    '\nvalue b is:' + $("select option:selected").data('valueb')_x000D_
  )_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>_x000D_
<select name="Testing">_x000D_
  <option value="1" data-valuea="2010" data-valueb="2011"> One_x000D_
    <option value="2" data-valuea="2122" data-valueb="2123"> Two_x000D_
      <option value="3" data-valuea="0" data-valueb="1"> Three_x000D_
</select>
_x000D_
_x000D_
_x000D_

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Get last n lines of a file, similar to tail

Several of these solutions have issues if the file doesn't end in \n or in ensuring the complete first line is read.

def tail(file, n=1, bs=1024):
    f = open(file)
    f.seek(-1,2)
    l = 1-f.read(1).count('\n') # If file doesn't end in \n, count it anyway.
    B = f.tell()
    while n >= l and B > 0:
            block = min(bs, B)
            B -= block
            f.seek(B, 0)
            l += f.read(block).count('\n')
    f.seek(B, 0)
    l = min(l,n) # discard first (incomplete) line if l > n
    lines = f.readlines()[-l:]
    f.close()
    return lines

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Use jQuery to scroll to the bottom of a div with lots of text

Scrolling with animation:

Your DIV:

<div class='messageScrollArea' style='height: 100px;overflow: auto;'>
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
</div>

jQuery part:

jQuery(document).ready(function(){       
    var $t = $('.messageScrollArea');
    $t.animate({"scrollTop": $('.messageScrollArea')[0].scrollHeight}, "slow");
});

?http://jsfiddle.net/3Wx3U/

Getting strings recognized as variable names in R

If you want to use a string as a variable name, you can use assign:

var1="string_name"

assign(var1, c(5,4,5,6,7))

string_name 

[1] 5 4 5 6 7

php - insert a variable in an echo string

Use double quotes:

$i = 1;
echo "
<p class=\"paragraph$i\">
</p>
";
++i;

Setting log level of message at runtime in slf4j

It is not possible to specify a log level in sjf4j 1.x out of the box. But there is hope for slf4j 2.0 to fix the issue. In 2.0 it might look like this:

// POTENTIAL 2.0 SOLUTION
import org.slf4j.helpers.Util;
import static org.slf4j.spi.LocationAwareLogger.*;

// does not work with slf4j 1.x
Util.log(logger, DEBUG_INT, "hello world!");

In the meanwhile, for slf4j 1.x, you can use this workaround:

Copy this class into your classpath:

import org.slf4j.Logger;
import java.util.function.Function;

public enum LogLevel {

    TRACE(l -> l::trace, Logger::isTraceEnabled),
    DEBUG(l -> l::debug, Logger::isDebugEnabled),
    INFO(l -> l::info, Logger::isInfoEnabled),
    WARN(l -> l::warn, Logger::isWarnEnabled),
    ERROR(l -> l::error, Logger::isErrorEnabled);

    interface LogMethod {
        void log(String format, Object... arguments);
    }

    private final Function<Logger, LogMethod> logMethod;
    private final Function<Logger, Boolean> isEnabledMethod;

    LogLevel(Function<Logger, LogMethod> logMethod, Function<Logger, Boolean> isEnabledMethod) {
        this.logMethod = logMethod;
        this.isEnabledMethod = isEnabledMethod;
    }

    public LogMethod prepare(Logger logger) {
        return logMethod.apply(logger);
    }

    public boolean isEnabled(Logger logger) {
        return isEnabledMethod.apply(logger);
    }
}

Then you can use it like this:

Logger logger = LoggerFactory.getLogger(Application.class);

LogLevel level = LogLevel.ERROR;
level.prepare(logger).log("It works!"); // just message, without parameter
level.prepare(logger).log("Hello {}!", "world"); // with slf4j's parameter replacing

try {
    throw new RuntimeException("Oops");
} catch (Throwable t) {
    level.prepare(logger).log("Exception", t);
}

if (level.isEnabled(logger)) {
    level.prepare(logger).log("logging is enabled");
}

This will output a log like this:

[main] ERROR Application - It works!
[main] ERROR Application - Hello world!
[main] ERROR Application - Exception
java.lang.RuntimeException: Oops
    at Application.main(Application.java:14)
[main] ERROR Application - logging is enabled

Is it worth it?

  • Pro It keeps the source code location (class names, method names, line numbers will point to your code)
  • Pro You can easily define variables, parameters and return types as LogLevel
  • Pro Your business code stays short and easy to read, and no additional dependencies required.

The source code as minimal example is hosted on GitHub.

How to get a view table query (code) in SQL Server 2008 Management Studio

if i understood you can do the following

Right Click on View Name in SQL Server Management Studio -> Script View As ->CREATE To ->New Query Window

How do I get milliseconds from epoch (1970-01-01) in Java?

How about System.currentTimeMillis()?

From the JavaDoc:

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Java 8 introduces the java.time framework, particularly the Instant class which "...models a ... point on the time-line...":

long now = Instant.now().toEpochMilli();

Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)

Cheers,

How to round up integer division and have int result in Java?

Another one-liner that is not too complicated:

private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

Could use long instead of int; just change the parameter types and return type.

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

After the file name in the HTML code I add ?forcedownload=1

This has been the simplest way for me to trigger a dialog box to save or download.

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

X-Frame-Options: ALLOW-FROM in firefox and chrome

ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options

You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?

Fixed header, footer with scrollable content

Approach 1 - flexbox

It works great for both known and unknown height elements. Make sure to set the outer div to height: 100%; and reset the default margin on body. See the browser support tables.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  flex: 1;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 2 - CSS table

For both known and unknown height elements. It also works in legacy browsers including IE8.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: table;_x000D_
}_x000D_
.header, .content, .footer {_x000D_
  display: table-row;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.inner {_x000D_
  display: table-cell;_x000D_
}_x000D_
.content .inner {_x000D_
  height: 100%;_x000D_
  position: relative;_x000D_
  background: pink;_x000D_
}_x000D_
.scrollable {_x000D_
  position: absolute;_x000D_
  left: 0; right: 0;_x000D_
  top: 0; bottom: 0;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">_x000D_
    <div class="inner">Header</div>_x000D_
  </div>_x000D_
  <div class="content">_x000D_
    <div class="inner">_x000D_
      <div class="scrollable">_x000D_
        <div style="height:1000px;">Content</div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="footer">_x000D_
    <div class="inner">Footer</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 3 - calc()

If header and footer are fixed height, you can use CSS calc().

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 50px;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: calc(100% - 100px);_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 4 - % for all

If the header and footer are known height, and they are also percentage you can just do the simple math making them together of 100% height.

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 10%;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: 80%;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

How to properly validate input values with React.JS?

yet another go at the same problem - form-container on npm

How to access SVG elements with Javascript

Is it possible to do it this way, as opposed to using something like Raphael or jQuery SVG?

Definitely.

If it is possible, what's the technique?

This annotated code snippet works:

<!DOCTYPE html>
<html>
    <head>
        <title>SVG Illustrator Test</title> 
    </head>
    <body>

        <object data="alpha.svg" type="image/svg+xml"
         id="alphasvg" width="100%" height="100%"></object>

        <script>
            var a = document.getElementById("alphasvg");

            // It's important to add an load event listener to the object,
            // as it will load the svg doc asynchronously
            a.addEventListener("load",function(){

                // get the inner DOM of alpha.svg
                var svgDoc = a.contentDocument;
                // get the inner element by id
                var delta = svgDoc.getElementById("delta");
                // add behaviour
                delta.addEventListener("mousedown",function(){
                        alert('hello world!')
                }, false);
            }, false);
        </script>
    </body>
</html>

Note that a limitation of this technique is that it is restricted by the same-origin policy, so alpha.svg must be hosted on the same domain as the .html file, otherwise the inner DOM of the object will be inaccessible.

Important thing to run this HTML, you need host HTML file to web server like IIS, Tomcat

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

i was also getting this error, remove oracle folder from

C:\Program Files (x86)\Oracle\Inventory

and

C:\Program Files\Oracle\Inventory

Also remove all component of oracle other version (which you had already in your system).

Go to services and remove all oracle component and delete old client from

C:\app\username\product\11.2.0\client_1\

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

How to use ng-if to test if a variable is defined

Try this:

item.shipping!==undefined

How do I get the last character of a string using an Excel function?

No need to apologize for asking a question! Try using the RIGHT function. It returns the last n characters of a string.

=RIGHT(A1, 1)

jQuery .load() call doesn't execute JavaScript in loaded HTML file

I ran into this where the scripts would load once, but repeat calls would not run the script.

It turned out to be an issue with using .html() to display a wait indicator and then chaining .load() after it.

// Processes scripts as expected once per page load, but not for repeat calls
$("#id").html("<img src=wait.gif>").load("page.html");

When I made them separate calls, my inline scripts loaded every time as expected.

// Without chaining html and load together, scripts are processed as expected every time
$("#id").html("<img src=wait.gif>");
$("#id").load("page.html");

For further research, note that there are two versions of .load()

A simple .load() call (without a selector after the url) is simply a shorthand for calling $.ajax() with dataType:"html" and taking the return contents and calling .html() to put those contents in the DOM. And the documentation for dataType:"html" clearly states "included script tags are evaluated when inserted in the DOM." http://api.jquery.com/jquery.ajax/ So .load() officially runs inline scripts.

A complex .load() call has a selector such as load("page.html #content"). When used that way, jQuery purposefully filters out script tags as discussed in articles like this one: https://forum.jquery.com/topic/the-load-function-and-script-blocks#14737000000752785 In this case the scripts never run, not even once.

Loop through a Map with JSTL

Like this:

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>
</c:forEach>

Margin while printing html page

Updated, Simple Solution

@media print {
   body {
       display: table;
       table-layout: fixed;
       padding-top: 2.5cm;
       padding-bottom: 2.5cm;
       height: auto;
   }
}

Old Solution

Create section with each page, and use the below code to adjust margins, height and width.

If you are printing A4 size.

Then user

Size : 8.27in and 11.69 inches

@page Section1 {
    size: 8.27in 11.69in; 
    margin: .5in .5in .5in .5in; 
    mso-header-margin: .5in; 
    mso-footer-margin: .5in; 
    mso-paper-source: 0;
}



div.Section1 {
    page: Section1;
} 

then create a div with all your content in it.

<div class="Section1"> 
    type your content here... 
</div>

Using local makefile for CLion instead of CMake

I am not very familiar with CMake and could not use Mondkin's solution directly.

Here is what I came up with in my CMakeLists.txt using the latest version of CLion (1.2.4) and MinGW on Windows (I guess you will just need to replace all: g++ mytest.cpp -o bin/mytest by make if you are not using the same setup):

cmake_minimum_required(VERSION 3.3)
project(mytest)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

add_custom_target(mytest ALL COMMAND mingw32-make WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

And the custom Makefile is like this (it is located at the root of my project and generates the executable in a bin directory):

all:
    g++ mytest.cpp -o bin/mytest

I am able to build the executable and errors in the log window are clickable.

Hints in the IDE are quite limited through, which is a big limitation compared to pure CMake projects...

How to go up a level in the src path of a URL in HTML?

Supposing you have the following file structure:

-css
  --index.css
-images
  --image1.png
  --image2.png
  --image3.png

In CSS you can access image1, for example, using the line ../images/image1.png.

NOTE: If you are using Chrome, it may doesn't work and you will get an error that the file could not be found. I had the same problem, so I just deleted the entire cache history from chrome and it worked.

In Chrome 55, prevent showing Download button for HTML 5 video

I solved the problem by covering the download button of a audio controller with a transparent div that changes the symbol of the mouse-cursor to "not-allowed".

The div blocks the activation of the download button.

Height: 50px, Width: 35px, Left: (document-right -60), Top: (same as the audio controller).

You must set the z-index style of the div above the z-index of the audio-controller.

See sapplic.com/jive66 for an example that works for chrome on win7 and on win8.

how to properly display an iFrame in mobile safari

The solution is to use Scrolling="no" on the iframe.

That's it.

How to compress an image via Javascript in the browser?

I find that there's simpler solution compared to the accepted answer.

  • Read the files using the HTML5 FileReader API with .readAsArrayBuffer
  • Create a Blob with the file data and get its url with window.URL.createObjectURL(blob)
  • Create new Image element and set it's src to the file blob url
  • Send the image to the canvas. The canvas size is set to desired output size
  • Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality)
  • Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text
  • On backend, read the dataURI, decode from Base64, and save it

As per your question:

Is there a way to compress an image (mostly jpeg, png and gif) directly browser-side, before uploading it

My solution:

  1. Create a blob with the file directly with URL.createObjectURL(inputFileElement.files[0]).

  2. Same as accepted answer.

  3. Same as accepted answer. Worth mentioning that, canvas size is necessary and use img.width and img.height to set canvas.width and canvas.height. Not img.clientWidth.

  4. Get the scale-down image by canvas.toBlob(callbackfunction(blob){}, 'image/jpeg', 0.5). Setting 'image/jpg' has no effect. image/png is also supported. Make a new File object inside the callbackfunction body with let compressedImageBlob = new File([blob]).

  5. Add new hidden inputs or send via javascript . Server doesn't have to decode anything.

Check https://javascript.info/binary for all information. I came up the solution after reading this chapter.


Code:

    <!DOCTYPE html>
    <html>
    <body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
      Select image to upload:
      <input type="file" name="fileToUpload" id="fileToUpload" multiple>
      <input type="submit" value="Upload Image" name="submit">
    </form>
    </body>
    </html>

This code looks far less scary than the other answers..

Update:

One has to put everything inside img.onload. Otherwise canvas will not be able to get the image's width and height correctly as the time canvas is assigned.

    function upload(){
        var f = fileToUpload.files[0];
        var fileName = f.name.split('.')[0];
        var img = new Image();
        img.src = URL.createObjectURL(f);
        img.onload = function(){
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            canvas.toBlob(function(blob){
                    console.info(blob.size);
                    var f2 = new File([blob], fileName + ".jpeg");
                    var xhr = new XMLHttpRequest();
                    var form = new FormData();
                    form.append("fileToUpload", f2);
                    xhr.open("POST", "upload.php");
                    xhr.send(form);
            }, 'image/jpeg', 0.5);
        }
    }

3.4MB .png file compression test with image/jpeg argument set.

    |0.9| 777KB |
    |0.8| 383KB |
    |0.7| 301KB |
    |0.6| 251KB |
    |0.5| 219kB |

How to clone an InputStream?

The class below should do the trick. Just create an instance, call the "multiply" method, and provide the source input stream and the amount of duplicates you need.

Important: you must consume all cloned streams simultaneously in separate threads.

package foo.bar;

import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class InputStreamMultiplier {
    protected static final int BUFFER_SIZE = 1024;
    private ExecutorService executorService = Executors.newCachedThreadPool();

    public InputStream[] multiply(final InputStream source, int count) throws IOException {
        PipedInputStream[] ins = new PipedInputStream[count];
        final PipedOutputStream[] outs = new PipedOutputStream[count];

        for (int i = 0; i < count; i++)
        {
            ins[i] = new PipedInputStream();
            outs[i] = new PipedOutputStream(ins[i]);
        }

        executorService.execute(new Runnable() {
            public void run() {
                try {
                    copy(source, outs);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        return ins;
    }

    protected void copy(final InputStream source, final PipedOutputStream[] outs) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        int n = 0;
        try {
            while (-1 != (n = source.read(buffer))) {
                //write each chunk to all output streams
                for (PipedOutputStream out : outs) {
                    out.write(buffer, 0, n);
                }
            }
        } finally {
            //close all output streams
            for (PipedOutputStream out : outs) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

angular2 manually firing click event on particular element

This worked for me:

<button #loginButton ...

and inside the controller:

@ViewChild('loginButton') loginButton;
...
this.loginButton.getNativeElement().click();

How to group time by hour or by 10 minutes

In T-SQL you can:

SELECT [Date]
  FROM [FRIIB].[dbo].[ArchiveAnalog]
  GROUP BY [Date], DATEPART(hh, [Date])

or

by minute use DATEPART(mi, [Date])

or

by 10 minutes use DATEPART(mi, [Date]) / 10 (like Timothy suggested)

Last segment of URL in jquery

you can first remove if there is / at the end and then get last part of url

let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
  locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);

How to return a value from __init__ in Python?

From the documentation of __init__:

As a special constraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.

As a proof, this code:

class Foo(object):
    def __init__(self):
        return 2

f = Foo()

Gives this error:

Traceback (most recent call last):
  File "test_init.py", line 5, in <module>
    f = Foo()
TypeError: __init__() should return None, not 'int'

How do I get the value of a textbox using jQuery?

Noticed your comment about using it for email validation and needing a plugin, the validation plugin may help you, its located at http://bassistance.de/jquery-plugins/jquery-plugin-validation/, it comes with a e-mail rule as well.

Multi-line strings in PHP

To put the strings "l" and "vv" on separate lines in the code alone:

$xml = "l";
$xml .= "vv"
echo $xml;

In this instance you're saying to append .= the string to the end of the previous version of that string variable. Remember that = is only an assignment operator so in your original code you're assigning the variable a new string value.

To put the strings "l" and "vv" on separate lines in the echo alone:

$xml = "l\nvv"
echo $xml;

You don't need multiple strings in this instance, as the new line character \n will take care of that for you.

To put the strings "l" and "vv" on separate lines in code and when echoing:

$xml = "l";
$xml .= "\nvv"
echo $xml;

How to add AUTO_INCREMENT to an existing column?

This worked for me in case you want to change the AUTO_INCREMENT-attribute for a not-empty-table:

1.)Exported the whole table as .sql file
2.)Deleted the table after export
2.)Did needed change in CREATE_TABLE command
3.)Executed the CREATE_TABLE and INSERT_INTO commands from the .sql-file
...et viola

"Untrusted App Developer" message when installing enterprise iOS Application

In iOS 9.1 and lower, go to Settings - General - Profiles - tap on your Profile - tap on Trust button.

How to pass a view's onClick event to its parent on Android?

Put

android:duplicateParentState="true"

in child then the views get its drawable state (focused, pressed, etc.) from its direct parent rather than from itself. you can set onclick for parent and it call on child clicked

findViewByID returns null

I had this same problem. I was using a third-party library that allows you to override their adapter for a GridView and to specify your own layout for each GridView cell.

I finally realized what was happening. Eclipse was still using the library's layout xml file for each cell in the GridView, even though it gave no indication of this. In my custom adapter, it indicated that it was using the xml resource from my own project even though at runtime, it wasn't.

So what I did was to make sure my custom xml layouts and ids were different from those still sitting in the library, cleaned the project and then it started reading the correct custom layouts that were in my project.

In short, be careful if you're overriding a third-party library's adapter and specifying your own layout xml for the adapter to use. If your layout inside your project has the same file name as that in the library, you might encounter a really difficult-to-find bug!

How to create a Java cron job

You can use TimerTask for Cronjobs.

Main.java

public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     MyTask mTask = new MyTask();
     // This task is scheduled to run every 10 seconds

     t.scheduleAtFixedRate(mTask, 0, 10000);
   }

}

MyTask.java

class MyTask extends TimerTask{

   public MyTask(){
     //Some stuffs
   }

   @Override
   public void run() {
     System.out.println("Hi see you after 10 seconds");
   }

}

Alternative You can also use ScheduledExecutorService.

'int' object has no attribute '__getitem__'

The error:

'int' object has no attribute '__getitem__'

means that you're attempting to apply the index operator [] on an int, not a list. So is col not a list, even when it should be? Let's start from that.

Look here:

col = [[0 for col in range(5)] for row in range(6)]

Use a different variable name inside, looks like the list comprehension overwrites the col variable during iteration. (Not during the iteration when you set col, but during the following ones.)

Is there any way to prevent input type="number" getting negative values?

The answer to this is not helpful. as its only works when you use up/down keys, but if you type -11 it will not work. So here is a small fix that I use

this one for integers

  $(".integer").live("keypress keyup", function (event) {
    //    console.log('int = '+$(this).val());
    $(this).val($(this).val().replace(/[^\d].+/, ""));
    if (event.which != 8 && (event.which < 48 || event.which > 57))
    {
        event.preventDefault();
    }
   });

this one when you have numbers of price

        $(".numeric, .price").live("keypress keyup", function (event) {
     //    console.log('numeric = '+$(this).val());
    $(this).val($(this).val().replace(/[^0-9\,\.]/g, ''));

    if (event.which != 8 && (event.which != 44 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
   });

How to filter in NaN (pandas)?

This doesn't work because NaN isn't equal to anything, including NaN. Use pd.isnull(df.var2) instead.

How to get all enum values in Java?

Enums are just like Classes in that they are typed. Your current code just checks if it is an Enum without specifying what type of Enum it is a part of.

Because you haven't specified the type of the enum, you will have to use reflection to find out what the list of enum values is.

You can do it like so:

enumValue.getDeclaringClass().getEnumConstants() 

This will return an array of Enum objects, with each being one of the available options.

How do I remove the horizontal scrollbar in a div?

With overflow-y: scroll, the vertical scrollbar will always be there even if it is not needed. If you want y-scrollbar to be visible only when it is needed, I found this works:

.mydivclass {overflow-x: hidden; overflow-y: auto;}

Android Studio: Unable to start the daemon process

In Eclipse, go to windows -> preferences -> gradle->arguments. Find JVM Arguments choose from radio button "USE :" and write arguments -Xms128m -Xmx512m Then click button Apply

Merge Cell values with PHPExcel - PHP

$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p)); for dynamic merging of cells

How to uninstall Apache with command line

Try this :

sc delete Apache2.4

or try this :

C:\Apache24\bin>httpd -k uninstall

hope this will be helpful

File inside jar is not visible for spring

I had similar problem when using Tomcat6.x and none of the advices I found was helping. At the end I deleted work folder (of Tomcat) and the problem gone.

I know it is illogical but for documentation purpose...

How to remove trailing and leading whitespace for user-provided input in a batch file?

I had to create a Function.

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION


set "TextString=    Purple Cows are flying in the Air Tonight         "
echo REM ^^Notice there is whitespace at the start and end of the TextString
echo "!TextString!"
CALL:trimWhiteSpace "!TextString!" OutPutString
echo Resulting Trimmed Text: "!OutPutString!"
echo REM ^^Now there should be no White space at the start or end.

Exit /B

Add this to the bottom of your batch file:

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B


::TRIM FUNCTIONS AREA::
:: USAGE:
:: trimWhiteSpace "!InputText!" OutputText
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: trimWhiteSpace "!InputText!" !OutputText!
:: ^^Because it has a ! around the OutPutText
:: Make Sure to add " around the InputText when running the call.
:: If you don't add the " then it will only accept the first word before a space.
::Example:
::  set "TextString=    Purple Cows are flying in the Air Tonight         "
::  echo REM ^^Notice there is whitespace at the start and end of the TextString
::  echo "!TextString!"
::  CALL:trimWhiteSpace "!TextString!" OutPutString
::  echo Resulting Trimmed Text: "!OutPutString!"
::  echo REM ^^Now there should be no White space at the start or end.

:trimWhiteSpace
set textToTrim=%~1
CALL:trimWhiteSpaceOnTheRight "!textToTrim!" OutPutString
SET textToTrim=!OutPutString!
CALL:trimWhiteSpaceOnTheLeft "!textToTrim!" OutPutString
SET %2=!OutPutString!
GOTO:EOF

:trimWhiteSpaceOnTheRight
set str=%~1
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
SET %2=%str%
GOTO:EOF

:trimWhiteSpaceOnTheLeft
set str=%~1
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
SET %2=%str%
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

How to get current user in asp.net core

It would appear that as of now (April of 2017) that the following works:

public string LoggedInUser => User.Identity.Name;

At least while within a Controller

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

In my case, spring threw this because i forgot to make an inner class static.

When you found that it doesnt help even adding a no-arg constructor, please check your modifier.

Select2 doesn't work when embedded in a bootstrap modal

I had a similar problem and I fixed with

    $('#CompId').select2({
              dropdownParent: $('#AssetsModal')
    });

and modal with select

    <div class="modal fade" id="AssetsModal" role="dialog" 
    aria-labelledby="exampleModalCenterTitle" 
    aria-hidden="true"  style="overflow:hidden;" >
<div class="modal-dialog modal-dialog-centered" role="document">
  <div class="modal-content">
      <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLongTitle" >?????? ??????</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
      </div>
      <div class="modal-body">
          <form role="form" action="?action=dma_act_documents_assets_insert&Id=<?=$ID?>" 
                  method="post" name="dma_act_documents_assets_insert" 
                  id="dma_act_documents_assets_insert">
            <div class="form-group col-sm-12">
                  <label for="recipient-name" class="col-form-label">?????:</label>
                  <span style="color: red">*</span>
                          <select class="form-control js-example-basic-single col-sm-12" 
                                 name="CompId" id="CompId">
                                  <option></option>
                          </select>
              </div>
          </form>
      </div>
  </div>
</div>

but I don't know why the select menu is smaller than other fields enter image description here

and it starting like that when start using select2. When I remove it, all is ok.

Is there some one to share some experince about that.

Thanks.

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

How to check if the user can go back in browser history or not

I came up with the following approach. It utilizes the onbeforeunload event to detect whether the browser starts leaving the page or not. If it does not in a certain timespan it'll just redirect to the fallback.

var goBack = function goBack(fallback){
    var useFallback = true;

    window.addEventListener("beforeunload", function(){
      useFallback = false;
    });

    window.history.back();

    setTimeout(function(){
        if (useFallback){ window.location.href = fallback; }
    }, 100); 
}

You can call this function using goBack("fallback.example.org").

Type Checking: typeof, GetType, or is?

if (c is UserControl) c.Enabled = enable;

Empty responseText from XMLHttpRequest

PROBLEM RESOLVED

In my case the problem was that I do the ajax call (with $.ajax, $.get or $.getJSON methods from jQuery) with full path in the url param:

url: "http://mydomain.com/site/cgi-bin/serverApp.php"

But the correct way is to pass the value of url as:

url: "site/cgi-bin/serverApp.php"

Some browser don't conflict and make no distiction between one text or another, but in Firefox 3.6 for Mac OS take this full path as "cross site scripting"... another thing, in the same browser there is a distinction between:

http://mydomain.com/site/index.html

And put

http://www.mydomain.com/site/index.html

In fact it is the correct point view, but most implementations make no distinction, so the solution was to remove all the text that specify the full path to the script in the methods that do the ajax request AND.... remove any BASE tag in the index.html file

base href="http://mydomain.com/" <--- bad idea, remove it!

If you don't remove it, this version of browser for this system may take your ajax request like if it is a cross site request!

I have the same problem but only on the Mac OS machine. The problem is that Firefox treat the ajax response as an "cross site" call, in any other machine/browser it works fine. I didn't found any help about this (I think that is a firefox implementation issue), but I'm going to prove the next code at the server side:

header('Content-type: application/json');

to ensure that browser get the data as "json data" ...

Equivalent of Oracle's RowID in SQL Server

You can get the ROWID by using the methods given below :

1.Create a new table with auto increment field in it

2.Use Row_Number analytical function to get the sequence based on your requirement.I would prefer this because it helps in situations where you are you want the row_id on ascending or descending manner of a specific field or combination of fields

Sample:Row_Number() Over(Partition by Deptno order by sal desc)

Above sample will give you the sequence number based on highest salary of each department.Partition by is optional and you can remove it according to your requirements

Remove first 4 characters of a string with PHP

You could use the substr function please check following example,

$string1 = "tarunmodi";
$first4 = substr($string1, 4);
echo $first4;

Output: nmodi

Datatable select with multiple conditions

Try this,
I think ,this is one of the simple solutions.

int rowIndex = table.Rows.IndexOf(table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'")[0]);
string strD= Convert.ToString(table.Rows[rowIndex]["D"]);

Make sure,combination of values for column A, B and C is unique in the datatable.

Exclude subpackages from Spring autowiring?

It seems you've done this through XML, but if you were working in new Spring best practice, your config would be in Java, and you could exclude them as so:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "net.example.tool",
  excludeFilters = {@ComponentScan.Filter(
    type = FilterType.ASSIGNABLE_TYPE,
    value = {JPAConfiguration.class, SecurityConfig.class})
  })

How to get a Docker container's IP address from the host

I had to extract docker container IP Adress by docker container name for further usage in deployment scripts. For this purpose I have written the following bash command:

docker inspect $(sudo docker ps | grep my_container_name | head -c 12) | grep -e \"IPAddress\"\:[[:space:]]\"[0-2] | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'

Suppose it could be handy to place it into a bash script, which would expect my_container_name as an argument...

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

Count number of 1's in binary representation

Please note the fact that: n&(n-1) always eliminates the least significant 1.

Hence we can write the code for calculating the number of 1's as follows:

count=0;
while(n!=0){
  n = n&(n-1);
  count++;
}
cout<<"Number of 1's in n is: "<<count;

The complexity of the program would be: number of 1's in n (which is constantly < 32).

Find number of decimal places in decimal value regardless of culture

I use the following mechanism in my code

  public static int GetDecimalLength(string tempValue)
    {
        int decimalLength = 0;
        if (tempValue.Contains('.') || tempValue.Contains(','))
        {
            char[] separator = new char[] { '.', ',' };
            string[] tempstring = tempValue.Split(separator);

            decimalLength = tempstring[1].Length;
        }
        return decimalLength;
    }

decimal input=3.376; var instring=input.ToString();

call GetDecimalLength(instring)

Opening database file from within SQLite command-line shell

The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.

select * from ttt.table_name;

or if table name in all attached databases is unique

select * from my_unique_table_name;

But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential

normally you would use sqlite-command-line in a script

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

you can use LocalRegistry such as:

Registry rgsty = LocateRegistry.createRegistry(1888);
rgsty.rebind("hello", hello);

how to refresh page in angular 2

Just in case someone else encounters this problem. You need to call

window.location.reload()

And you cannot call this from a expression. If you want to call this from a click event you need to put this on a function:

(click)="realodPage()"

And simply define the function:

reloadPage() {
   window.location.reload();
}

If you are changing the route, it might not work because the click event seems to happen before the route changes. A very dirty solution is just to add a small delay

reloadPage() {
    setTimeout(()=>{
      window.location.reload();
    }, 100);
}

How to get Device Information in Android

Try this:

// Code For IMEI AND IMSI NUMBER

String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
String IMEI,IMSI;
IMEI = m_telephonyManager.getDeviceId();
IMSI = m_telephonyManager.getSubscriberId();

Trimming text strings in SQL Server 2008

This function trims a string from left and right. Also it removes carriage returns from the string, an action which is not done by the LTRIM and RTRIM

IF OBJECT_ID(N'dbo.TRIM', N'FN') IS NOT NULL
    DROP FUNCTION dbo.TRIM;
GO
CREATE FUNCTION dbo.TRIM (@STR NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)
BEGIN
    RETURN(LTRIM(RTRIM(REPLACE(REPLACE(@STR ,CHAR(10),''),CHAR(13),''))))
END;
GO

How can I temporarily disable a foreign key constraint in MySQL?

To turn off foreign key constraint globally, do the following:

SET GLOBAL FOREIGN_KEY_CHECKS=0;

and remember to set it back when you are done

SET GLOBAL FOREIGN_KEY_CHECKS=1;

WARNING: You should only do this when you are doing single user mode maintenance. As it might resulted in data inconsistency. For example, it will be very helpful when you are uploading large amount of data using a mysqldump output.

Creating Scheduled Tasks

You can use Task Scheduler Managed Wrapper:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}

Alternatively you can use native API or go for Quartz.NET. See this for details.

What's the difference between <b> and <strong>, <i> and <em>?

I use both <strong> and <b>, actually, for exactly the reasons mentioned in this thread of responses. There are times when bold-facing some text simply looks better, but it isn't, necessarily, semantically more important than the rest of the sentence. Here's an example from a page I'm working on right now:

"Retrieves <strong>all</strong> books about <b>lacrosse</b>."

In that sentence, the word "all" is very important, and "lacrosse" less so--I merely wanted it bold because it represents a search term, so I wanted some visual separation. If you're viewing the page with a screen reader, I really don't think it needs to go out of the way to emphasize the word "lacrosse".

I would tend to imagine that most web developers use one of the other, but both are fine--<b> is most definitely not deprecated, as some people have claimed. For me, it's just a fine line between visual appeal and meaning.

How can I remove the first line of a text file using bash/sed script?

No, that's about as efficient as you're going to get. You could write a C program which could do the job a little faster (less startup time and processing arguments) but it will probably tend towards the same speed as sed as files get large (and I assume they're large if it's taking a minute).

But your question suffers from the same problem as so many others in that it pre-supposes the solution. If you were to tell us in detail what you're trying to do rather then how, we may be able to suggest a better option.

For example, if this is a file A that some other program B processes, one solution would be to not strip off the first line, but modify program B to process it differently.

Let's say all your programs append to this file A and program B currently reads and processes the first line before deleting it.

You could re-engineer program B so that it didn't try to delete the first line but maintains a persistent (probably file-based) offset into the file A so that, next time it runs, it could seek to that offset, process the line there, and update the offset.

Then, at a quiet time (midnight?), it could do special processing of file A to delete all lines currently processed and set the offset back to 0.

It will certainly be faster for a program to open and seek a file rather than open and rewrite. This discussion assumes you have control over program B, of course. I don't know if that's the case but there may be other possible solutions if you provide further information.

What is the difference between ports 465 and 587?

SMTP protocol: smtps (port 465) v. msa (port 587)

Ports 465 and 587 are intended for email client to email server communication - sending out email using SMTP protocol.

Port 465 is for smtps
SSL encryption is started automatically before any SMTP level communication.

Port 587 is for msa
It is almost like standard SMTP port. MSA should accept email after authentication (e.g. after SMTP AUTH). It helps to stop outgoing spam when netmasters of DUL ranges can block outgoing connections to SMTP port (port 25).
SSL encryption may be started by STARTTLS command at SMTP level if server supports it and your ISP does not filter server's EHLO reply (reported 2014).


Port 25 is used by MTA to MTA communication (mail server to mail server). It may be used for client to server communication but it is not currently the most recommended. Standard SMTP port accepts email from other mail servers to its "internal" mailboxes without authentication.

Resize on div element

I was only interested for a trigger when a width of an element was changed (I don' care about height), so I created a jquery event that does exactly that, using an invisible iframe element.

$.event.special.widthChanged = {
  remove: function() {
      $(this).children('iframe.width-changed').remove();
  },
  add: function () {
      var elm = $(this);
      var iframe = elm.children('iframe.width-changed');
      if (!iframe.length) {
          iframe = $('<iframe/>').addClass('width-changed').prependTo(this);
      }
      var oldWidth = elm.width();
      function elmResized() {
          var width = elm.width();
          if (oldWidth != width) {
              elm.trigger('widthChanged', [width, oldWidth]);
              oldWidth = width;
          }
      }

      var timer = 0;
      var ielm = iframe[0];
      (ielm.contentWindow || ielm).onresize = function() {
          clearTimeout(timer);
          timer = setTimeout(elmResized, 20);
      };
  }
}

It requires the following css :

iframe.width-changed {
    width: 100%;
    display: block;
    border: 0;
    height: 0;
    margin: 0;
}

You can see it in action here widthChanged fiddle

Git: How do I list only local branches?

There's a great answer to a post about how to delete local only branches. In it, the fellow builds a command to list out the local branches:

git branch -vv | cut -c 3- | awk '$3 !~/\[/ { print $1 }'

The answer has a great explanation about how this command was derived, so I would suggest you go and read that post.

Why is the <center> tag deprecated in HTML?

HTML is intended for structuring data, not controlling layout. CSS is intended to control layout. You'll also find that many designers frown on using <table> for layouts for this very same reason.

How is "mvn clean install" different from "mvn install"?

Ditto for @Andreas_D, in addition if you say update Spring from 1 version to another in your project without doing a clean, you'll wind up with both in your artifact. Ran into this a lot when doing Flex development with Maven.

What is boilerplate code?

From Wikipedia:

In computer programming, boilerplate is the term used to describe sections of code that have to be included in many places with little or no alteration. It is more often used when referring to languages that are considered verbose, i.e. the programmer must write a lot of code to do minimal jobs.

So basically you can consider boilerplate code as a text that is needed by a programming language very often all around the programs you write in that language.

Modern languages are trying to reduce it, but also the older language which has specific type-checkers (for example OCaml has a type-inferrer that allows you to avoid so many declarations that would be boilerplate code in a more verbose language like Java)

How can I get dictionary key as variable directly in Python (not by searching from value)?

keys=[i for i in mydictionary.keys()] or keys = list(mydictionary.keys())

how to call a variable in code behind to aspx page

In your code behind file, have a public variable

public partial class _Default : System.Web.UI.Page
{
    public string clients;

    protected void Page_Load(object sender, EventArgs e)
    {
        // your code that at one points sets the variable
        this.clients = "abc";
    }
}

now in your design code, just assign that to something, like:

<div>
    <p><%= clients %></p>
</div>

or even a javascript variable

<script type="text/javascript">

    var clients = '<%= clients %>';

</script>

How can I set selected option selected in vue.js 2?

Handling the errors

You are binding properties to nothing. :required in

<select class="form-control" v-model="selected" :required @change="changeLocation">

and :selected in

<option :selected>Choose Province</option>

If you set the code like so, your errors should be gone:

<template>
  <select class="form-control" v-model="selected" :required @change="changeLocation">
    <option>Choose Province</option>
    <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
 </select>
</template>

Getting the select tags to have a default value

  1. you would now need to have a data property called selected so that v-model works. So,

    {
      data () {
        return {
          selected: "Choose Province"
        }
      }
    }
    
  2. If that seems like too much work, you can also do it like:

    <template>
      <select class="form-control" :required="true" @change="changeLocation">
       <option :selected="true">Choose Province</option>
       <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
      </select>
    </template>
    

When to use which method?

  1. You can use the v-model approach if your default value depends on some data property.

  2. You can go for the second method if your default selected value happens to be the first option.

  3. You can also handle it programmatically by doing so:

    <select class="form-control" :required="true">
      <option 
       v-for="option in options" 
       v-bind:value="option.id"
       :selected="option == '<the default value you want>'"
      >{{ option }}</option>
    </select>
    

Selenium WebDriver and DropDown Boxes

public static void mulptiTransfer(WebDriver driver, By dropdownID, String text, By to)
{   
    String valuetext = null;
    WebElement element = locateElement(driver, dropdownID, 10);
    Select select = new Select(element);
    List<WebElement> options = element.findElements(By.tagName("option"));
    for (WebElement value: options) 
    {
        valuetext = value.getText();
        if (valuetext.equalsIgnoreCase(text))
        {
            try
            {
                select.selectByVisibleText(valuetext);
                locateElement(driver, to, 5).click();                           
                break;
            }
            catch (Exception e)
            {
                System.out.println(valuetext + "Value not found in Dropdown to Select");
            }       
        }
    }
}

NLS_NUMERIC_CHARACTERS setting for decimal

Jaanna, the session parameters in Oracle SQL Developer are dependent on your client computer, while the NLS parameters on PL/SQL is from server.

For example the NLS_NUMERIC_CHARACTERS on client computer can be ',.' while it's '.,' on server.

So when you run script from PL/SQL and Oracle SQL Developer the decimal separator can be completely different for the same script, unless you alter session with your expected NLS_NUMERIC_CHARACTERS in the script.

One way to easily test your session parameter is to do:

select to_number(5/2) from dual;

Regex match entire words only

Use word boundaries:

/\b($word)\b/i

Or if you're searching for "S.P.E.C.T.R.E." like in Sinan Ünür's example:

/(?:\W|^)(\Q$word\E)(?:\W|$)/i

Java: Best way to iterate through a Collection (here ArrayList)

There is additionally collections’ stream() util with Java 8

collection.forEach((temp) -> {
            System.out.println(temp);
});

or

collection.forEach(System.out::println);

More information about Java 8 stream and collections for wonderers link

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

How to upload multiple files using PHP, jQuery and AJAX

My solution

  • Assuming that form id = "my_form_id"
  • It detects the form method and form action from HTML

jQuery code

$('#my_form_id').on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData($(this)[0]);
    var msg_error = 'An error has occured. Please try again later.';
    var msg_timeout = 'The server is not responding';
    var message = '';
    var form = $('#my_form_id');
    $.ajax({
        data: formData,
        async: false,
        cache: false,
        processData: false,
        contentType: false,
        url: form.attr('action'),
        type: form.attr('method'),
        error: function(xhr, status, error) {
            if (status==="timeout") {
                alert(msg_timeout);
            } else {
                alert(msg_error);
            }
        },
        success: function(response) {
            alert(response);
        },
        timeout: 7000
    });
});

Retrieve data from a ReadableStream object?

Little bit late to the party but had some problems with getting something useful out from a ReadableStream produced from a Odata $batch request using the Sharepoint Framework.

Had similar issues as OP, but the solution in my case was to use a different conversion method than .json(). In my case .text() worked like a charm. Some fiddling was however necessary to get some useful JSON from the textfile.

Pass variables by reference in JavaScript

JavaScript not being strong type. It allows you to resolve problems in many different ways, as it seem in this question.

However, for a maintainability point of view, I would have to agree with Bart Hofland. A function should get arguments to do something with and return the result. Making them easily reusable.

If you feel that variables need to be passed by reference, you may be better served building them into objects, IMHO.

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

Convert number to varchar in SQL with formatting

Here's an alternative following the last answer

declare @t tinyint,@v tinyint
set @t=23
set @v=232
Select replace(str(@t,4),' ','0'),replace(str(@t,5),' ','0')

This will work on any number and by varying the length of the str() function you can stipulate how many leading zeros you require. Provided of course that your string length is always >= maximum number of digits your number type can hold.

Convert bytes to bits in python

Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.

If you want bit 7 and 8 only, use e.g.

val = (byte >> 6) & 3

(this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits 3 is the number with the first two bits set...)

These can easily be translated into simple CPU operations that are super fast.

Using jQuery to programmatically click an <a> link

I had similar issue. try this $('#myAnchor').get(0).click();this works for me

Java 8 forEach with index

There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:

int idx = 0;
for (Param p : params) query.bind(idx++, p);

Or the older style:

for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));

Creating default object from empty value in PHP?

no you do not .. it will create it when you add the success value to the object.the default class is inherited if you do not specify one.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

Q: If PyPy can solve these great challenges (speed, memory consumption, parallelism) in comparison to CPython, what are its weaknesses that are preventing wider adoption?

A: First, there is little evidence that the PyPy team can solve the speed problem in general. Long-term evidence is showing that PyPy runs certain Python codes slower than CPython and this drawback seems to be rooted very deeply in PyPy.

Secondly, the current version of PyPy consumes much more memory than CPython in a rather large set of cases. So PyPy didn't solve the memory consumption problem yet.

Whether PyPy solves the mentioned great challenges and will in general be faster, less memory hungry, and more friendly to parallelism than CPython is an open question that cannot be solved in the short term. Some people are betting that PyPy will never be able to offer a general solution enabling it to dominate CPython 2.7 and 3.3 in all cases.

If PyPy succeeds to be better than CPython in general, which is questionable, the main weakness affecting its wider adoption will be its compatibility with CPython. There also exist issues such as the fact that CPython runs on a wider range of CPUs and OSes, but these issues are much less important compared to PyPy's performance and CPython-compatibility goals.


Q: Why can't I do drop in replacement of CPython with PyPy now?

A: PyPy isn't 100% compatible with CPython because it isn't simulating CPython under the hood. Some programs may still depend on CPython's unique features that are absent in PyPy such as C bindings, C implementations of Python object&methods, or the incremental nature of CPython's garbage collector.

Can .NET load and parse a properties file equivalent to Java Properties class?

I don't know of any built-in way to do this. However, it would seem easy enough to do, since the only delimiters you have to worry about are the newline character and the equals sign.

It would be very easy to write a routine that will return a NameValueCollection, or an IDictionary given the contents of the file.

Only detect click event on pseudo-element

My answer will work for anyone wanting to click a definitive area of the page. This worked for me on my absolutely-positioned :after

Thanks to this article, I realized (with jQuery) I can use e.pageY and e.pageX instead of worrying about e.offsetY/X and e.clientY/X issue between browsers.

Through my trial and error, I started to use the clientX and clientY mouse coordinates in the jQuery event object. These coordinates gave me the X and Y offset of the mouse relative to the top-left corner of the browser's view port. As I was reading the jQuery 1.4 Reference Guide by Karl Swedberg and Jonathan Chaffer, however, I saw that they often referred to the pageX and pageY coordinates. After checking the updated jQuery documentation, I saw that these were the coordinates standardized by jQuery; and, I saw that they gave me the X and Y offset of the mouse relative to the entire document (not just the view port).

I liked this event.pageY idea because it would always be the same, as it was relative to the document. I can compare it to my :after's parent element using offset(), which returns its X and Y also relative to the document.

Therefore, I can come up with a range of "clickable" region on the entire page that never changes.


Here's my demo on codepen.


or if too lazy for codepen, here's the JS:

* I only cared about the Y values for my example.

var box = $('.box');
// clickable range - never changes
var max = box.offset().top + box.outerHeight();
var min = max - 30; // 30 is the height of the :after

var checkRange = function(y) {
  return (y >= min && y <= max);
}

box.click(function(e){
  if ( checkRange(e.pageY) ) {
    // do click action
    box.toggleClass('toggle');
  }
});

PDO get the last ID inserted

lastInsertId() only work after the INSERT query.

Correct:

$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                              VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0