Programs & Examples On #Frontpage

Frontpage is a design tool for web publishing which was part of Microsoft Office

Nested routes with react router v4 / v5

You can try something like Routes.js

import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import FrontPage from './FrontPage';
import Dashboard from './Dashboard';
import AboutPage from './AboutPage';
import Backend from './Backend';
import Homepage from './Homepage';
import UserPage from './UserPage';
class Routes extends Component {
    render() {
        return (
            <div>
                <Route exact path="/" component={FrontPage} />
                <Route exact path="/home" component={Homepage} />
                <Route exact path="/about" component={AboutPage} />
                <Route exact path="/admin" component={Backend} />
                <Route exact path="/admin/home" component={Dashboard} />
                <Route exact path="/users" component={UserPage} />    
            </div>
        )
    }
}

export default Routes

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Routes from './Routes';

class App extends Component {
  render() {
    return (
      <div className="App">
      <Router>
        <Routes/>
      </Router>
      </div>
    );
  }
}

export default App;

I think you can achieve the same from here also.

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I have also got stuck into this and believe me disabling SELinux is not a good idea.

Please just use below and you are good,

sudo restorecon -R /var/www/mysite

Enjoy..

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

Animate background image change with jQuery

It can be done by jquery and css. i did it in a way that can be used in dynamic situations , you just have to change background-image in jquery and it will do every thing , also you can change the time in css.

The fiddle : https://jsfiddle.net/Naderial/zohfvqz7/

Html:

<div class="test">

CSS :

.test {
  /* as default, we set a background-image , but it is not nessesary */
  background-image: url(http://lorempixel.com/400/200);
  width: 200px;
  height: 200px;
  /* we set transition to 'all' properies - but you can use it just for background image either - by default the time is set to 1 second, you can change it yourself*/
  transition: linear all 1s;
  /* if you don't use delay , background will disapear and transition will start from a white background - you have to set the transition-delay the same as transition time OR more , so there won't be any problems */
  -webkit-transition-delay: 1s;/* Safari */
  transition-delay: 1s;
}

JS:

$('.test').click(function() {
  //you can use all properties : background-color  - background-image ...
  $(this).css({
    'background-image': 'url(http://lorempixel.com/400/200)'
  });
});

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

The first error you're getting - permissions - is the most indicative. Bump wp-content and wp-admin to 777 and try it, and if it works, then change them both back to 755 and see if it still works. What are you using to change folder permissions? An FTP client?

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

In my case I parsed an S3 url into its components.

For example:

Url:    s3://bucket-name/path/to/file

Was parsed into:

Bucket: bucket-name
Path:   /path/to/file

Having the path part containing a leading '/' failed the request.

What is the difference between YAML and JSON?

Technically YAML offers a lot more than JSON (YAML v1.2 is a superset of JSON):

  • comments
  • anchors and inheritance - example of 3 identical items:

    item1: &anchor_name
      name: Test
      title: Test title
    item2: *anchor_name
    item3:
      <<: *anchor_name
      # You may add extra stuff.
    
  • ...

Most of the time people will not use those extra features and the main difference is that YAML uses indentation whilst JSON uses brackets. This makes YAML more concise and readable (for the trained eye).

Which one to choose?

  • YAML extra features and concise notation makes it a good choice for configuration files (non-user provided files).
  • JSON limited features, wide support, and faster parsing makes it a great choice for interoperability and user provided data.

How to get the last character of a string in a shell?

For portability you can say "${s#"${s%?}"}":

#!/bin/sh
m=bzzzM n=bzzzN
for s in \
    'vv'  'w'   ''    'uu  ' ' uu ' '  uu' / \
    'ab?' 'a?b' '?ab' 'ab??' 'a??b' '??ab' / \
    'cd#' 'c#d' '#cd' 'cd##' 'c##d' '##cd' / \
    'ef%' 'e%f' '%ef' 'ef%%' 'e%%f' '%%ef' / \
    'gh*' 'g*h' '*gh' 'gh**' 'g**h' '**gh' / \
    'ij"' 'i"j' '"ij' "ij'"  "i'j"  "'ij"  / \
    'kl{' 'k{l' '{kl' 'kl{}' 'k{}l' '{}kl' / \
    'mn$' 'm$n' '$mn' 'mn$$' 'm$$n' '$$mn' /
do  case $s in
    (/) printf '\n' ;;
    (*) printf '.%s. ' "${s#"${s%?}"}" ;;
    esac
done

Output:

.v. .w. .. . . . . .u. 
.?. .b. .b. .?. .b. .b. 
.#. .d. .d. .#. .d. .d. 
.%. .f. .f. .%. .f. .f. 
.*. .h. .h. .*. .h. .h. 
.". .j. .j. .'. .j. .j. 
.{. .l. .l. .}. .l. .l. 
.$. .n. .n. .$. .n. .n. 

Regular expression which matches a pattern, or is an empty string

To match pattern or an empty string, use

^$|pattern

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively.
  • | is used to denote alternates, e.g. this|that.

References


On \b

\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.

That is, \b is located:

  • Between consecutive \w and \W (either order):
    • i.e. between a word character and a non-word character
  • Between ^ and \w
    • i.e. at the beginning of the string if it starts with \w
  • Between \w and $
    • i.e. at the end of the string if it ends with \w

References


On using regex to match e-mail addresses

This is not trivial depending on specification.

Related questions

DateTime format to SQL format using C#

try this below

DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

The 'json' native gem requires installed build tools

I have found that the error is sometimes caused by a missing library.

so If you install RDOC first by running

gem install rdoc

then install rails with:

gem install rails

then go back and install the devtools as mentioned before with:

1) Extract DevKit to path C:\Ruby193\DevKit
2) cd C:\Ruby192\DevKit
3) ruby dk.rb init
4) ruby dk.rb review
5) ruby dk.rb install

then try installing json

which culminate with you finally being able to run

rails new project_name - without errors.

good luck

How to return a file (FileContentResult) in ASP.NET WebAPI

This question helped me.

So, try this:

Controller code:

[HttpGet]
public HttpResponseMessage Test()
{
    var path = System.Web.HttpContext.Current.Server.MapPath("~/Content/test.docx");;
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentLength = stream.Length;
    return result;          
}

View Html markup (with click event and simple url):

<script type="text/javascript">
    $(document).ready(function () {
        $("#btn").click(function () {
            // httproute = "" - using this to construct proper web api links.
            window.location.href = "@Url.Action("GetFile", "Data", new { httproute = "" })";
        });
    });
</script>


<button id="btn">
    Button text
</button>

<a href=" @Url.Action("GetFile", "Data", new { httproute = "" }) ">Data</a>

Decorators with parameters?

In case both the function and the decorator have to take arguments you can follow the below approach.

For example there is a decorator named decorator1 which takes an argument

@decorator1(5)
def func1(arg1, arg2):
    print (arg1, arg2)

func1(1, 2)

Now if the decorator1 argument has to be dynamic, or passed while calling the function,

def func1(arg1, arg2):
    print (arg1, arg2)


a = 1
b = 2
seconds = 10

decorator1(seconds)(func1)(a, b)

In the above code

  • seconds is the argument for decorator1
  • a, b are the arguments of func1

add image to uitableview cell

Try this code:--

UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:@"arrow2.png"];
[cell addSubview:imv];
[imv release];

Composer killed while updating

If like me, you are using some micro VM lacking of memory, creating a swap file does the trick:

#Check free memory before
free -m

mkdir -p /var/_swap_
cd /var/_swap_
#Here, 1M * 2000 ~= 2GB of swap memory.  Feel free to add MORE
dd if=/dev/zero of=swapfile bs=1M count=2000
chmod 600 swapfile
mkswap swapfile
swapon swapfile
#Automatically mount this swap partition at startup
echo "/var/_swap_/swapfile none swap sw 0 0" >> /etc/fstab

#Check free memory after
free -m

As several comments pointed out, don't forget to add sudo if you don't work as root.

btw, feel free to select another location/filename/size for the file.
/var is probably not the best place, but I don't know which place would be, and rarely care since tiny servers are mostly used for testing purposes.

SELECT inside a COUNT

SELECT a AS current_a, COUNT(*) AS b,
   (SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
   from t group by a order by b desc

What is thread Safe in java?

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.

Trying to merge 2 dataframes but get ValueError

Additional: when you save df to .csv format, the datetime (year in this specific case) is saved as object, so you need to convert it into integer (year in this specific case) when you do the merge. That is why when you upload both df from csv files, you can do the merge easily, while above error will show up if one df is uploaded from csv files and the other is from an existing df. This is somewhat annoying, but have an easy solution if kept in mind.

How to make a transparent HTML button?

To get rid of the outline when clicking, add outline:none

jsFiddle example

button {
    background-color: Transparent;
    background-repeat:no-repeat;
    border: none;
    cursor:pointer;
    overflow: hidden;
    outline:none;
}

_x000D_
_x000D_
button {_x000D_
    background-color: Transparent;_x000D_
    background-repeat:no-repeat;_x000D_
    border: none;_x000D_
    cursor:pointer;_x000D_
    overflow: hidden;_x000D_
    outline:none;_x000D_
}
_x000D_
<button>button</button>
_x000D_
_x000D_
_x000D_

Java Currency Number format

I was crazy enough to write my own function:

This will convert integer to currency format (can be modified for decimals as well):

 String getCurrencyFormat(int v){
        String toReturn = "";
        String s =  String.valueOf(v);
        int length = s.length();
        for(int i = length; i >0 ; --i){
            toReturn += s.charAt(i - 1);
            if((i - length - 1) % 3 == 0 && i != 1) toReturn += ',';
        }
        return "$" + new StringBuilder(toReturn).reverse().toString();
    }

Git error: src refspec master does not match any

The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:

git push origin master

Which will create this new master branch for you. Little things like this are very confusing with git.

If this didn't fix your issue then it's probably a gitolite-related issue:

Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:

repo    phonegap                                                                                                                                                                           
    RW+     =   myusername otherusername                                                                                                                                               

repo    gitolite-admin                                                                                                                                                                         
    RW+     =   myusername                                                                                                                                                               

Please make sure you're setting your conf file correctly.

Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.

Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.

How to determine the encoding of text?

It is, in principle, impossible to determine the encoding of a text file, in the general case. So no, there is no standard Python library to do that for you.

If you have more specific knowledge about the text file (e.g. that it is XML), there might be library functions.

How can I add numbers in a Bash script?

 #!/bin/bash
read X
read Y
echo "$(($X+$Y))"

How to stop "setInterval"

Store the return of setInterval in a variable, and use it later to clear the interval.

var timer = null;
$("textarea").blur(function(){
    timer = window.setInterval(function(){ ... whatever ... }, 2000);
}).focus(function(){
    if(timer){
       window.clearInterval(timer);
       timer = null
    }
});

Default interface methods are only supported starting with Android N

This also happened to me but using Dynamic Features. I already had Java 8 compatibility enabled in the app module but I had to add this compatibility lines to the Dynamic Feature module and then it worked.

What Language is Used To Develop Using Unity

You can use C#, Javascript, Boo.

Unless computing requirement for the function you write cause heavy load on processor, Javascript gives good enough performance for most cases.

Replace all particular values in a data frame

Like this:

> df[df==""]<-NA
> df
     A    B
1 <NA>   12
2  xyz <NA>
3  jkl  100

Python - Get path of root project structure

I've recently been trying to do something similar and I have found these answers inadequate for my use cases (a distributed library that needs to detect project root). Mainly I've been battling different environments and platforms, and still haven't found something perfectly universal.

Code local to project

I've seen this example mentioned and used in a few places, Django, etc.

import os
print(os.path.dirname(os.path.abspath(__file__)))

Simple as this is, it only works when the file that the snippet is in is actually part of the project. We do not retrieve the project directory, but instead the snippet's directory

Similarly, the sys.modules approach breaks down when called from outside the entrypoint of the application, specifically I've observed a child thread cannot determine this without relation back to the 'main' module. I've explicitly put the import inside a function to demonstrate an import from a child thread, moving it to top level of app.py would fix it.

app/
|-- config
|   `-- __init__.py
|   `-- settings.py
`-- app.py

app.py

#!/usr/bin/env python
import threading


def background_setup():
    # Explicitly importing this from the context of the child thread
    from config import settings
    print(settings.ROOT_DIR)


# Spawn a thread to background preparation tasks
t = threading.Thread(target=background_setup)
t.start()

# Do other things during initialization

t.join()

# Ready to take traffic

settings.py

import os
import sys


ROOT_DIR = None


def setup():
    global ROOT_DIR
    ROOT_DIR = os.path.dirname(sys.modules['__main__'].__file__)
    # Do something slow

Running this program produces an attribute error:

>>> import main
>>> Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python2714\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python2714\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "main.py", line 6, in background_setup
    from config import settings
  File "config\settings.py", line 34, in <module>
    ROOT_DIR = get_root()
  File "config\settings.py", line 31, in get_root
    return os.path.dirname(sys.modules['__main__'].__file__)
AttributeError: 'module' object has no attribute '__file__'

...hence a threading-based solution

Location independent

Using the same application structure as before but modifying settings.py

import os
import sys
import inspect
import platform
import threading


ROOT_DIR = None


def setup():
    main_id = None
    for t in threading.enumerate():
        if t.name == 'MainThread':
            main_id = t.ident
            break

    if not main_id:
        raise RuntimeError("Main thread exited before execution")

    current_main_frame = sys._current_frames()[main_id]
    base_frame = inspect.getouterframes(current_main_frame)[-1]

    if platform.system() == 'Windows':
        filename = base_frame.filename
    else:
        filename = base_frame[0].f_code.co_filename

    global ROOT_DIR
    ROOT_DIR = os.path.dirname(os.path.abspath(filename))

Breaking this down: First we want to accurately find the thread ID of the main thread. In Python3.4+ the threading library has threading.main_thread() however, everybody doesn't use 3.4+ so we search through all threads looking for the main thread save it's ID. If the main thread has already exited, it won't be listed in the threading.enumerate(). We raise a RuntimeError() in this case until I find a better solution.

main_id = None
for t in threading.enumerate():
    if t.name == 'MainThread':
        main_id = t.ident
        break

if not main_id:
    raise RuntimeError("Main thread exited before execution")

Next we find the very first stack frame of the main thread. Using the cPython specific function sys._current_frames() we get a dictionary of every thread's current stack frame. Then utilizing inspect.getouterframes() we can retrieve the entire stack for the main thread and the very first frame. current_main_frame = sys._current_frames()[main_id] base_frame = inspect.getouterframes(current_main_frame)[-1] Finally, the differences between Windows and Linux implementations of inspect.getouterframes() need to be handled. Using the cleaned up filename, os.path.abspath() and os.path.dirname() clean things up.

if platform.system() == 'Windows':
    filename = base_frame.filename
else:
    filename = base_frame[0].f_code.co_filename

global ROOT_DIR
ROOT_DIR = os.path.dirname(os.path.abspath(filename))

So far I've tested this on Python2.7 and 3.6 on Windows as well as Python3.4 on WSL

Bash mkdir and subfolders

To create multiple sub-folders

mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}

Is it possible to disable scrolling on a ViewPager

The answer of slayton works fine. If you want to stop swiping like a monkey you can override a OnPageChangeListener with

@Override public void onPageScrollStateChanged(final int state) { 
        switch (state) { 
            case ViewPager.SCROLL_STATE_SETTLING: 
                mPager.setPagingEnabled(false); 
                break; 
            case ViewPager.SCROLL_STATE_IDLE: 
                mPager.setPagingEnabled(true); 
                break; 
        } 
    }

So you can only swipe side by side

Can't load AMD 64-bit .dll on a IA 32-bit platform

Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.

How do I find out which keystore was used to sign an app?

You can use Java 7's Key and Certificate Management Tool keytool to check the signature of a keystore or an APK without extracting any files.

Signature of an APK or AAB

# APK file
keytool -printcert -jarfile app.apk

# AAB file
keytool -printcert -jarfile app.aab

The output will reveal the signature owner/issuer and MD5, SHA1 and SHA256 fingerprints of the APK file app.apk or AAB file app.aab.

(Note that the -jarfile argument was introduced in Java 7; see the documentation for more details.)

Signature of a keystore

keytool -list -v -keystore release.jks

The output will reveal the aliases (entries) in the keystore file release.jks, with the certificate fingerprints (MD5, SHA1 and SHA256).

If the SHA1 fingerprints between the APK and the keystore match, then you can rest assured that that app is signed with the key.

Delete a row from a table by id

Something quick and dirty:

<script type='text/javascript'>
function del_tr(remtr)  
{   
    while((remtr.nodeName.toLowerCase())!='tr')
        remtr = remtr.parentNode;

    remtr.parentNode.removeChild(remtr);
}
function del_id(id)  
{   
        del_tr(document.getElementById(id));
}
</script>

if you place

<a href='' onclick='del_tr(this);return false;'>x</a>

anywhere within the row you want to delete, than its even working without any ids

Eclipse CDT project built but "Launch Failed. Binary Not Found"

After trying everything here what worked for me was to grant execution permission to eclipse:

cd eclipse-installation-dir 
sudo chmod +x eclipse

Using Eclipse Luna on Ubuntu 12.04 LTS.

How to obtain the last index of a list?

a = ['1', '2', '3', '4']
print len(a) - 1
3

DateTime and CultureInfo

You may try the following:

System.Globalization.CultureInfo cultureinfo =
        new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);

C: How to free nodes in the linked list?

An iterative function to free your list:

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

What the function is doing is the follow:

  1. check if head is NULL, if yes the list is empty and we just return

  2. Save the head in a tmp variable, and make head point to the next node on your list (this is done in head = head->next

  3. Now we can safely free(tmp) variable, and head just points to the rest of the list, go back to step 1

What __init__ and self do in Python?

In this code:

class Cat:
    def __init__(self, name):
        self.name = name
    def info(self):
        print 'I am a cat and I am called', self.name

Here __init__ acts as a constructor for the class and when an object is instantiated, this function is called. self represents the instantiating object.

c = Cat('Kitty')
c.info()

The result of the above statements will be as follows:

I am a cat and I am called Kitty

How can I pop-up a print dialog box using Javascript?

I like this, so that you can add whatever fields you want and print it that way.

function printPage() {
    var w = window.open();

    var headers =  $("#headers").html();
    var field= $("#field1").html();
    var field2= $("#field2").html();

    var html = "<!DOCTYPE HTML>";
    html += '<html lang="en-us">';
    html += '<head><style></style></head>';
    html += "<body>";

    //check to see if they are null so "undefined" doesnt print on the page. <br>s optional, just to give space
    if(headers != null) html += headers + "<br/><br/>";
    if(field != null) html += field + "<br/><br/>";
    if(field2 != null) html += field2 + "<br/><br/>";

    html += "</body>";
    w.document.write(html);
    w.window.print();
    w.document.close();
};

How to convert a date to milliseconds

tl;dr

LocalDateTime.parse(           // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
    "2014/10/29 18:10:45"      // Convert input string to comply with standard ISO 8601 format.
    .replace( " " , "T" )      // Replace SPACE in the middle with a `T`.
    .replace( "/" , "-" )      // Replace SLASH in the middle with a `-`.
)
.atZone(                       // Apply a time zone to provide the context needed to determine an actual moment.
    ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
)                              // Returns a `ZonedDateTime` object.
.toInstant()                   // Adjust into UTC.
.toEpochMilli()                // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.

1414602645000

Time Zone

The accepted answer is correct, except that it ignores the crucial issue of time zone. Is your input string 6:10 PM in Paris or Montréal? Or UTC?

Use a proper time zone name. Usually a continent plus city/region. For example, "Europe/Oslo". Avoid the 3 or 4 letter codes which are neither standardized nor unique.

java.time

The modern approach uses the java.time classes.

Alter your input to conform with the ISO 8601 standard. Replace the SPACE in the middle with a T. And replace the slash characters with hyphens. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

A LocalDateTime, like your input string, lacks any concept of time zone or offset-from-UTC. Without the context of a zone/offset, a LocalDateTime has no real meaning. Is it 6:10 PM in India, Europe, or Canada? Each of those places experience 6:10 PM at different moments, at different points on the timeline. So you must specify which you have in mind if you want to determine a specific point on the timeline.

ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  

Now we have a specific moment, in that ZonedDateTime. Convert to UTC by extracting a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant() ;

Now we can get your desired count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.

long millisSinceEpoch = instant.toEpochMilli() ; 

Be aware of possible data loss. The Instant object is capable of carrying microseconds or nanoseconds, finer than milliseconds. That finer fractional part of a second will be ignored when getting a count of milliseconds.


About java.time

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

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

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

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

Where to obtain the java.time classes?

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


Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I will leave this section intact for history.

Below is the same kind of code but using the Joda-Time 2.5 library and handling time zone.

The java.util.Date, .Calendar, and .SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the java.time package (inspired by Joda-Time) built into Java 8.

ISO 8601

Your string is almost in ISO 8601 format. The slashes need to be hyphens and the SPACE in middle should be replaced with a T. If we tweak that, then the resulting string can be fed directly into constructor without bothering to specify a formatter. Joda-Time uses ISO 8701 formats as it's defaults for parsing and generating strings.

Example Code

String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi
EOF

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    #!/bin/bash
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
    else
      exit 1
    fi
EOF

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

How do I create a constant in Python?

There's no perfect way to do this. As I understand it most programmers will just capitalize the identifier, so PI = 3.142 can be readily understood to be a constant.

On the otherhand, if you want something that actually acts like a constant, I'm not sure you'll find it. With anything you do there will always be some way of editing the "constant" so it won't really be a constant. Here's a very simple, dirty example:

def define(name, value):
  if (name + str(id(name))) not in globals():
    globals()[name + str(id(name))] = value

def constant(name):
  return globals()[name + str(id(name))]

define("PI",3.142)

print(constant("PI"))

This looks like it will make a PHP-style constant.

In reality all it takes for someone to change the value is this:

globals()["PI"+str(id("PI"))] = 3.1415

This is the same for all the other solutions you'll find on here - even the clever ones that make a class and redefine the set attribute method - there will always be a way around them. That's just how Python is.

My recommendation is to just avoid all the hassle and just capitalize your identifiers. It wouldn't really be a proper constant but then again nothing would.

Getting a better understanding of callback functions in JavaScript

You can just say

callback();

Alternately you can use the call method if you want to adjust the value of this within the callback.

callback.call( newValueForThis);

Inside the function this would be whatever newValueForThis is.

Vlookup referring to table data in a different sheet

I have faced similar problem and it was returning #N/A. That means matching data is present but you might having extra space in the M3 column record, that may prevent it from getting exact value. Because you have set last parameter as FALSE, it is looking for "exact match". This formula is correct: =VLOOKUP(M3,Sheet1!$A$2:$Q$47,13,FALSE)

Beginner Python: AttributeError: 'list' object has no attribute

Consider:

class Bike(object):
    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),      # <--
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165),    # <--
    }

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin
    print(profit)

Output:

33.0
20.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

this will occur when you try to call .cost on a list object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost -- in this line:

profit = bike.cost * margin

This indicates that at least one bike (that is, a member of bikes.values() is a list). If you look at where you defined bikes you can see that the values were, in fact, lists. So this error makes sense.

But since your class has a cost attribute, it looked like you were trying to use Bike instances as values, so I made that little change:

[...] -> Bike(...)

and you're all set.

What does the KEY keyword mean?

KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

column_definition:
      data_type [NOT NULL | NULL] [DEFAULT default_value]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      ...

Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Replacement for "rename" in dplyr

dplyr >= 1.0.0

In addition to dplyr::rename in newer versions of dplyr is rename_with()

rename_with() renames columns using a function.

You can apply a function over a tidy-select set of columns using the .cols argument:

iris %>% 
  dplyr::rename_with(.fn = ~ gsub("^S", "s", .), .cols = where(is.numeric))

    sepal.Length sepal.Width Petal.Length Petal.Width    Species
1            5.1         3.5          1.4         0.2     setosa
2            4.9         3.0          1.4         0.2     setosa
3            4.7         3.2          1.3         0.2     setosa
4            4.6         3.1          1.5         0.2     setosa
5            5.0         3.6          1.4         0.2     setosa

how I can show the sum of in a datagridview column?

Use LINQ if you can.

  label1.Text =  dataGridView1.Rows.Cast<DataGridViewRow>()
                                   .AsEnumerable()
                                   .Sum(x => int.Parse(x.Cells[1].Value.ToString()))
                                   .ToString();

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the setXxx() methods on PreparedStatement, while the SQL query string does not have any placeholders ? for this.

For example this is wrong:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

You need to fix the SQL query string accordingly to specify the placeholders.

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

Note the parameter index starts with 1 and that you do not need to quote those placeholders like so:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

See also:

How do I set a fixed background image for a PHP file?

It's not a good coding to put PHP code into CSS

body
{
    background-image:url('bg.png');
}

that's it

How can I get zoom functionality for images?

This is a very late addition to this thread but I've been working on an image view that supports zoom and pan and has a couple of features I haven't found elsewhere. This started out as a way of displaying very large images without causing OutOfMemoryErrors, by subsampling the image when zoomed out and loading higher resolution tiles when zoomed in. It now supports use in a ViewPager, rotation manually or using EXIF information (90° stops), override of selected touch events using OnClickListener or your own GestureDetector or OnTouchListener, subclassing to add overlays, pan while zooming, and fling momentum.

It's not intended as a general use replacement for ImageView so doesn't extend it, and doesn't support display of images from resources, only assets and external files. It requires SDK 10.

Source is on GitHub, and there's a sample that illustrates use in a ViewPager.

https://github.com/davemorrissey/subsampling-scale-image-view

Github "Updates were rejected because the remote contains work that you do not have locally."

This happens if you initialized a new github repo with README and/or LICENSE file

git remote add origin [//your github url]

//pull those changes

git pull origin master 

// or optionally, 'git pull origin master --allow-unrelated-histories' if you have initialized repo in github and also committed locally

//now, push your work to your new repo

git push origin master

Now you will be able to push your repository to github. Basically, you have to merge those new initialized files with your work. git pull fetches and merges for you. You can also fetch and merge if that suits you.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

I was working with Spring REST, and I solved it adding the AllowedMethods into the WebMvcConfigurer.

@Value( "${app.allow.origins}" )
    private String allowOrigins;    
@Bean
public WebMvcConfigurer corsConfigurer() {
            System.out.println("allow origin: "+allowOrigins);
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**")
                    //.allowedOrigins("http://localhost")
                    .allowedOrigins(allowOrigins)
                    .allowedMethods("PUT", "DELETE","GET", "POST");
                }
            };
        }

ERROR 1148: The used command is not allowed with this MySQL version

I find the answer here.

It's because the server variable local_infile is set to FALSE|0. Refer from the document.

You can verify by executing:

SHOW VARIABLES LIKE 'local_infile';

If you have SUPER privilege you can enable it (without restarting server with a new configuration) by executing:

SET GLOBAL local_infile = 1;

JavaScript adding decimal numbers issue

Testing this Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixed works very well.

How to break long string to multiple lines

you may simply create your string in multiple steps, a bit redundant but it keeps the code readable and maintain sanity while debugging or editing

SqlQueryString = "Insert into Employee values(" 
SqlQueryString = SqlQueryString & txtEmployeeNo.Value & " ,"
SqlQueryString = SqlQueryString & " '" & txtEmployeeNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtFloor.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtLeaves.Value & "' )"

Set Google Chrome as the debugging browser in Visual Studio

If you don't see the "Browse With..." option stop debugging first. =)

Convert dictionary to list collection in C#

Alternatively:

var keys = new List<string>(dicNumber.Keys);

spark submit add multiple jars in classpath

Pass --jars with the path of jar files separated by , to spark-submit.

For reference:

--driver-class-path is used to mention "extra" jars to add to the "driver" of the spark job

--driver-library-path is used to "change" the default library path for the jars needed for the spark driver

--driver-class-path will only push the jars to the driver machine. If you want to send the jars to "executors", you need to use --jars

And to set the jars programatically set the following config: spark.yarn.dist.jars with comma-separated list of jars.

Eg:

from pyspark.sql import SparkSession

spark = SparkSession \
        .builder \
        .appName("Spark config example") \
        .config("spark.yarn.dist.jars", "<path-to-jar/test1.jar>,<path-to-jar/test2.jar>") \
        .getOrCreate()

How can I install the Beautiful Soup module on the Mac?

The "normal" way is to:

Another solution is to use easy_install. Go to http://peak.telecommunity.com/DevCenter/EasyInstall), install the package using the instructions on that page, and then type, in a Terminal window:

easy_install BeautifulSoup4
# for older v3:
# easy_install BeautifulSoup

easy_install will take care of downloading, unpacking, building, and installing the package. The advantage to using easy_install is that it knows how to search for many different Python packages, because it queries the PyPI registry. Thus, once you have easy_install on your machine, you install many, many different third-party packages simply by one command at a shell.

WPF MVVM: How to close a window

I've been searching for a solution to the same problem and found that doing following works fine. The solution is similar to what OP has mentioned in his question with some differences:

  1. No need of IsCancel property.

  2. Code behind should not close window. Just set DialogResult

In my case it first executes code behind and then view model command bound to the button.

XAML

<Button x:Name="buttonOk" Click="Save_Click" Command="{Binding SaveCommand}">OK</Button>

Code Behind

private void Apply_OnClick(object sender, RoutedEventArgs e)
{
    this.DialogResult = true;
}

View Model

private void Save()
{
 // Save data.
}

Hope this helps.

Executing an EXE file using a PowerShell script

Not being a developer I found a solution in running multiple ps commands in one line. E.g:

powershell "& 'c:\path with spaces\to\executable.exe' -arguments ; second command ; etc

By placing a " (double quote) before the & (ampersand) it executes the executable. In none of the examples I have found this was mentioned. Without the double quotes the ps prompt opens and waits for input.

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

You can always format a date by extracting the parts and combine them using string functions:

_x000D_
_x000D_
var date = new Date();_x000D_
var dateStr =_x000D_
  ("00" + (date.getMonth() + 1)).slice(-2) + "/" +_x000D_
  ("00" + date.getDate()).slice(-2) + "/" +_x000D_
  date.getFullYear() + " " +_x000D_
  ("00" + date.getHours()).slice(-2) + ":" +_x000D_
  ("00" + date.getMinutes()).slice(-2) + ":" +_x000D_
  ("00" + date.getSeconds()).slice(-2);_x000D_
console.log(dateStr);
_x000D_
_x000D_
_x000D_

How do I configure different environments in Angular.js?

You could use lvh.me:9000 to access your AngularJS app, (lvh.me just points to 127.0.0.1) and then specify a different endpoint if lvh.me is the host:

app.service("Configuration", function() {
  if (window.location.host.match(/lvh\.me/)) {
    return this.API = 'http://localhost\\:7080/myapi/';
  } else {
    return this.API = 'http://localhost\\:8099/hisapi/';
  }
});

And then inject the Configuration service and use Configuration.API wherever you need to access the API:

$resource(Configuration.API + '/endpoint/:id', {
  id: '@id'
});

A tad clunky, but works fine for me, albeit in a slightly different situation (API endpoints differ in production and development).

Renew Provisioning Profile

I went to the Program Portal on Apple's dev site, clicked on Provisioning, clicked on the "Renew" button next to my Profile, the status changed from 'expired' to 'pending', waited a few moments, clicked refresh, the new status was active until 3 months from now, I clicked on "Download", found the downloaded file in my downloads folder, and dragged it onto my XCode Icon. (I had Xcode running already, and had the iphone plugged in). The new profile showed up, and I deleted the old one (being careful because they had the same name, but when you mouse over them the expiration date appears).

I think because I had the phone plugged in already it automagically updated to the phone, because I didn't have to re-sync or anything.

Now my App works again!

Parallel.ForEach vs Task.Factory.StartNew

The first is a much better option.

Parallel.ForEach, internally, uses a Partitioner<T> to distribute your collection into work items. It will not do one task per item, but rather batch this to lower the overhead involved.

The second option will schedule a single Task per item in your collection. While the results will be (nearly) the same, this will introduce far more overhead than necessary, especially for large collections, and cause the overall runtimes to be slower.

FYI - The Partitioner used can be controlled by using the appropriate overloads to Parallel.ForEach, if so desired. For details, see Custom Partitioners on MSDN.

The main difference, at runtime, is the second will act asynchronous. This can be duplicated using Parallel.ForEach by doing:

Task.Factory.StartNew( () => Parallel.ForEach<Item>(items, item => DoSomething(item)));

By doing this, you still take advantage of the partitioners, but don't block until the operation is complete.

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

How to install Java 8 on Mac

Java8 is no longer available on homebrew, brew install java8 will not work.

Instead, use:

brew cask install adoptopenjdk/openjdk/adoptopenjdk8

See this commit for technical details.

Please note as well you may see issues around Cask adoptopenjdk8 exists in multiple taps. This is a known issue, currently being worked on, which you can see here:

https://github.com/AdoptOpenJDK/homebrew-openjdk/issues/106

For those who don't want to run through the details, here is a summary:

# To install JDK8
brew cask install adoptopenjdk/openjdk/adoptopenjdk8

# To be able to safely run 'brew cleanup'
brew untap adoptopenjdk/openjdk
brew untap caskroom/versions
brew cleanup

How to access JSON Object name/value?

The JSON you are receiving is in string. You have to convert it into JSON object You have commented the most important line of code

data = JSON.parse(data);

Or if you are using jQuery

data = $.parseJSON(data)

How to workaround 'FB is not defined'?

You were very close with your original example. You could either use @jAndy's suggestion or:

if (typeof FB != 'undefined')

Can't escape the backslash with regex?

you can use ? at the end to skip one "\"

regex("\\\\?")

Redirect all output to file in Bash

That part is written to stderr, use 2> to redirect it. For example:

foo > stdout.txt 2> stderr.txt

or if you want in same file:

foo > allout.txt 2>&1

Note: this works in (ba)sh, check your shell for proper syntax

413 Request Entity Too Large - File Upload Issue

Source: http://www.cyberciti.biz/faq/linux-unix-bsd-nginx-413-request-entity-too-large/

Edit the conf file of nginx:

nano /etc/nginx/nginx.conf

Add a line in the http section:

http {
    client_max_body_size 100M;
}

Doen't use MB it will not work, only the M!

Also do not forget to restart nginx

systemctl restart nginx

Add space between <li> elements

Since you are asking for space between , I would add an override to the last item to get rid of the extra margin there:

_x000D_
_x000D_
li {_x000D_
  background: red;_x000D_
  margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
li:last-child {_x000D_
 margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  background: silver;_x000D_
  padding: 1px;  _x000D_
  padding-left: 40px;_x000D_
}
_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

The result of it might not be visual at all times, because of margin-collapsing and stuff... in the example snippets I've included, I've added a small 1px padding to the ul-element to prevent the collapsing. Try removing the li:last-child-rule, and you'll see that the last item now extends the size of the ul-element.

Run an OLS regression with Pandas Data Frame

I don't know if this is new in sklearn or pandas, but I'm able to pass the data frame directly to sklearn without converting the data frame to a numpy array or any other data types.

from sklearn import linear_model

reg = linear_model.LinearRegression()
reg.fit(df[['B', 'C']], df['A'])

>>> reg.coef_
array([  4.01182386e-01,   3.51587361e-04])

Directly assigning values to C Pointers

The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.

You need to create an int variable somewhere in memory for the int * variable to point at.

Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:

int main(){
    int variable;
    int *ptr = &variable;
    *ptr = 20;
    printf("%d", *ptr);
    return 0;
}

Here, the int variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20. The key is that the pointer is initialized to point to the variable. In fact, you could just allocate some raw memory to point to, if you want:

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

No notification sound when sending notification from firebase in android

do like this

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    //codes..,.,,

    Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(sound);

}

Semaphore vs. Monitors - what's the difference?

One Line Answer:

Monitor: controls only ONE thread at a time can execute in the monitor. (need to acquire lock to execute the single thread)

Semaphore: a lock that protects a shared resource. (need to acquire the lock to access resource)

FirstOrDefault: Default value other than null

From the documentation for FirstOrDefault

[Returns] default(TSource) if source is empty;

From the documentation for default(T):

the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.

Therefore, the default value can be null or 0 depending on whether the type is a reference or value type, but you cannot control the default behaviour.

How to grep a text file which contains some binary data?

grep -a will force grep to search and output from a file that grep thinks is binary. grep -a re test.log

display:inline vs display:block

Block

Takes up the full width available, with a new line before and after (display:block;)

Inline

Takes up only as much width as it needs, and does not force new lines (display:inline;)

On localhost, how do I pick a free port number?

Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname() right after bind().

How to loop through a HashMap in JSP?

Depending on what you want to accomplish within the loop, iterate over one of these instead:

  • countries.keySet()
  • countries.entrySet()
  • countries.values()

Javascript regular expression password validation having special characters

you can make your own regular expression for javascript validation

    /^            : Start
    (?=.{8,})        : Length
    (?=.*[a-zA-Z])   : Letters
    (?=.*\d)         : Digits
    (?=.*[!#$%&? "]) : Special characters
    $/              : End



        (/^
        (?=.*\d)                //should contain at least one digit
        (?=.*[a-z])             //should contain at least one lower case
        (?=.*[A-Z])             //should contain at least one upper case
        [a-zA-Z0-9]{8,}         //should contain at least 8 from the mentioned characters

        $/)

Example:-   /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{7,}$/

Stopping Docker containers by image name - Ubuntu

The previous answers did not work for me, but this did:

docker stop $(docker ps -q --filter ancestor=<image-name> )

Sort a list of tuples by 2nd item (integer value)

Adding to Cheeken's answer, This is how you sort a list of tuples by the 2nd item in descending order.

sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)

Copy files on Windows Command Line with Progress

Some interesting timings regarding all these methods. If you have Gigabit connections, you should not use the /z flag or it will kill your connection speed. Robocopy or dism are the only tools that go full speed and show a progress bar. wdscase is for multicasting off a WDS server and might be faster if you are imaging 5+ computers. To get the 1:17 timing, I was maxing out the Gigabit connection at 920Mbps so you won't get that on two connections at once. Also take note that exporting the small wim index out of the larger wim file too longer than just copying the whole thing.

Model  Exe       OS       switches     index    size    time   link speed 
8760w  dism      Win8     /export-wim  index 1  6.27GB  2:21   link 1Gbps
8760w  dism      Win8     /export-wim  index 2  7.92GB  1:29   link 1Gbps
6305   wdsmcast  winpe32  /trans-file  res.RWM  7.92GB  6:54   link 1Gbps
6305   dism      Winpe32  /export-wim  index 1  6.27GB  2:20   link 1Gbps
6305   dism      Winpe32  /export-wim  index 2  7.92GB  1:34   link 1Gbps
6305   copy      Winpe32  /z           Whole    7.92GB  25:48  link 1Gbps
6305   copy      Winpe32  none         Wim      7.92GB  1:17   link 1Gbps
6305   xcopy     Winpe32  /z /j        Wim      7.92GB  23:54  link 1Gbps
6305   xcopy     Winpe32  /j           Wim      7.92GB  1:38   link 1Gbps
6305   VBS.copy  Winpe32               Wim      7.92    1:21   link 1Gbps
6305   robocopy  Winpe32               Wim      7.92    1:17   link 1Gbps

If you don't have robocopy.exe available, why not run it from the network share you are copying your files from? In my case, I prefer to do that so I don't have to rebuild my WinPE boot.wim file every time I want to make a change and then update dozens of flash drives.

Installing Java on OS X 10.9 (Mavericks)

The OP implied that Java 7 was the need. And Java 6 is in fact no longer being 'supported' so 7 is the version you should be installing at this point unless you have legacy app concerns.

You can get it here: http://java.com/en/download/mac_download.jsp?locale=en

Expected corresponding JSX closing tag for input Reactjs

It happens when we do not close a html tag.

Make sure all the html tags are closed.

In my case it was the <br> tag. It should be <br />.

Try temporarily removing piece of code until you find which html tag closing is missing.

iterating over and removing from a map

ConcurrentHashMap

You can use java.util.concurrent.ConcurrentHashMap.

It implements ConcurrentMap (which extends the Map interface).

E.g.:

Map<Object, Content> map = new ConcurrentHashMap<Object, Content>();

for (Object key : map.keySet()) {
    if (something) {
        map.remove(key);
    }
}

This approach leaves your code untouched. Only the map type differs.

Plot smooth line with PyPlot

I presume you mean curve-fitting and not anti-aliasing from the context of your question. PyPlot doesn't have any built-in support for this, but you can easily implement some basic curve-fitting yourself, like the code seen here, or if you're using GuiQwt it has a curve fitting module. (You could probably also steal the code from SciPy to do this as well).

How Do I Uninstall Yarn

Try "npm uninstall -g yarnpkg"(global) or "npm uninstall yarnpkg"(local) if you installed it with npm.
That's what worked for me.
If that still doesn't work and you installed it with npm,
do "npm list -g" to check if you installed it globally or "npm list" if you installed it locally.
Hope that helps anyone having this problem. :D

EDIT: Found something if you installed yarn with .msi executable you have to install it the normal windows way.

How can I add an item to a IEnumerable<T> collection?

Not only can you not add items like you state, but if you add an item to a List<T> (or pretty much any other non-read only collection) that you have an existing enumerator for, the enumerator is invalidated (throws InvalidOperationException from then on).

If you are aggregating results from some type of data query, you can use the Concat extension method:

Edit: I originally used the Union extension in the example, which is not really correct. My application uses it extensively to make sure overlapping queries don't duplicate results.

IEnumerable<T> itemsA = ...;
IEnumerable<T> itemsB = ...;
IEnumerable<T> itemsC = ...;
return itemsA.Concat(itemsB).Concat(itemsC);

HTML how to clear input using javascript?

<script type="text/javascript">
    function clearThis(target){
        if(target.value=='[email protected]'){
        target.value= "";}
    }
    </script>

Is this really what your looking for?

Detect encoding and make everything UTF-8

Try without 'auto'

That is:

mb_detect_encoding($text)

instead of:

mb_detect_encoding($text, 'auto')

More information can be found here: mb_detect_encoding

How to customize Bootstrap 3 tab color

To have the active tab also styled, merge the answer from this thread, from Mansukh Khandhar, with this other answer, from lmgonzalves:

.nav-tabs > li.active > a {
  background-color: yellow !important;
  border: medium none;
  border-radius: 0;
}

Parsing JSON from URL

You could use org.apache.commons.io.IOUtils for downloading and org.json.JSONTokener for parsing:

JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));

Remove a fixed prefix/suffix from a string in Bash

I would make use of capture groups in regex:

$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ set +H # Disables history substitution, can be omitted in scripts.
$ perl -pe "s/${prefix}((?:(?!(${suffix})).)*)${suffix}/\1/" <<< $string
o-wor
$ string1=$string$string
$ perl -pe "s/${prefix}((?:(?!(${suffix})).)*)${suffix}/\1/g" <<< $string1
o-woro-wor

((?:(?!(${suffix})).)*) makes sure that the content of ${suffix} will be excluded from the capture group. In terms of example, it's the string equivalent to [^A-Z]*. Otherwise you will get:

$ perl -pe "s/${prefix}(.*)${suffix}/\1/g" <<< $string1
o-worldhello-wor

How to get the type of T from a member of a generic class or method?

This is how i did it

internal static Type GetElementType(this Type type)
{
        //use type.GenericTypeArguments if exist 
        if (type.GenericTypeArguments.Any())
         return type.GenericTypeArguments.First();

         return type.GetRuntimeProperty("Item").PropertyType);
}

Then call it like this

var item = Activator.CreateInstance(iListType.GetElementType());

OR

var item = Activator.CreateInstance(Bar.GetType().GetElementType());

Moment.js - how do I get the number of years since a date, not rounded up?

I prefer this small method.

function getAgeFromBirthday(birthday) {
    if(birthday){
      var totalMonths = moment().diff(birthday, 'months');
      var years = parseInt(totalMonths / 12);
      var months = totalMonths % 12;
        if(months !== 0){
           return parseFloat(years + '.' + months);
         }
    return years;
      }
    return null;
}

Using Mockito to test abstract classes

Mockito allows mocking abstract classes by means of the @Mock annotation:

public abstract class My {

    public abstract boolean myAbstractMethod();

    public void myNonAbstractMethod() {
        // ...
    }
}

@RunWith(MockitoJUnitRunner.class)
public class MyTest {

    @Mock(answer = Answers.CALLS_REAL_METHODS)
    private My my;

    @Test
    private void shouldPass() {
        BDDMockito.given(my.myAbstractMethod()).willReturn(true);
        my.myNonAbstractMethod();
        // ...
    }
}

The disadvantage is that it cannot be used if you need constructor parameters.

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

To easily understand the problem, imagine we wrote this code:

static void Main(string[] args)
{
    string[] test = new string[3];
    test[0]= "hello1";
    test[1]= "hello2";
    test[2]= "hello3";

    for (int i = 0; i <= 3; i++)
    {
        Console.WriteLine(test[i].ToString());
    }
}

Result will be:

hello1
hello2
hello3

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.

Size of array is 3 (indices 0, 1 and 2), but the for-loop loops 4 times (0, 1, 2 and 3).
So when it tries to access outside the bounds with (3) it throws the exception.

Questions every good PHP Developer should be able to answer

I'd ask something like:

a) what about caching?

b) how can cache be organised?

c) are you sure, you do not do extra DB queries? (In my first stuff I've made on PHP it was a mysql_query inside foreach to get names of users who've made comments... terrible :) )

d) why register_globals is evil?

e) why and how you should split view from code?

f) what is the main aim of "implement"?

Here are questions that were not clear at all for me after I've read some basic books. I've found out all about injections and csx, strpos in a few days\weeks through thousands of FAQs in the web. But until I found answers to these questions my code was really terrible :)

Read binary file as string in Ruby

To avoid leaving the file open, it is best to pass a block to File.open. This way, the file will be closed after the block executes.

contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }

When I catch an exception, how do I get the type, file, and line number?

Simplest form that worked for me.

import traceback

try:
    print(4/0)
except ZeroDivisionError:
    print(traceback.format_exc())

Output

Traceback (most recent call last):
  File "/path/to/file.py", line 51, in <module>
    print(4/0)
ZeroDivisionError: division by zero

Process finished with exit code 0

Laravel requires the Mcrypt PHP extension

sudo php install mcrypt

sudo php5enmod mcrypt

Wireshark localhost traffic capture

You can view loopback traffic live in Wireshark by having it read RawCap's output instantly. cmaynard describes this ingenious approach at the Wireshark forums. I will cite it here:

[...] if you want to view live traffic in Wireshark, you can still do it by running RawCap from one command-line and running Wireshark from another. Assuming you have cygwin's tail available, this could be accomplished using something like so:

cmd1: RawCap.exe -f 127.0.0.1 dumpfile.pcap

cmd2: tail -c +0 -f dumpfile.pcap | Wireshark.exe -k -i -

It requires cygwin's tail, and I could not find a way to do this with Windows' out-of-the-box tools. His approach works very fine for me and allows me to use all of Wiresharks filter capabilities on captured loopback traffic live.

Search all tables, all columns for a specific value SQL Server

You could query the sys.tables database view to get out the names of the tables, and then use this query to build yourself another query to do the update on the back of that. For instance:

select 'select * from '+name from sys.tables

will give you a script that will run a select * against all the tables in the system catalog, you could alter the string in the select clause to do your update, as long as you know the column name is the same on all the tables you wish to update, so your script would look something like:

select 'update '+name+' set comments = ''(*)''+comments where comments like ''%comment to be updated%'' ' from sys.tables

You could also then predicate on the tables query to only include tables that have a name in a certain format, or are in a subset you want to create the update script for.

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.

Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431

How to make HTML element resizable using pure Javascript?

Is simple:

Example:https://jsfiddle.net/RainStudios/mw786v1w/

var element = document.getElementById('element');
//create box in bottom-left
var resizer = document.createElement('div');
resizer.style.width = '10px';
resizer.style.height = '10px';
resizer.style.background = 'red';
resizer.style.position = 'absolute';
resizer.style.right = 0;
resizer.style.bottom = 0;
resizer.style.cursor = 'se-resize';
//Append Child to Element
element.appendChild(resizer);
//box function onmousemove
resizer.addEventListener('mousedown', initResize, false);

//Window funtion mousemove & mouseup
function initResize(e) {
   window.addEventListener('mousemove', Resize, false);
   window.addEventListener('mouseup', stopResize, false);
}
//resize the element
function Resize(e) {
   element.style.width = (e.clientX - element.offsetLeft) + 'px';
   element.style.height = (e.clientY - element.offsetTop) + 'px';
}
//on mouseup remove windows functions mousemove & mouseup
function stopResize(e) {
    window.removeEventListener('mousemove', Resize, false);
    window.removeEventListener('mouseup', stopResize, false);
}

100% width Twitter Bootstrap 3 template

Using Bootstrap 3.3.5 and .container-fluid, this is how I get full width with no gutters or horizontal scrolling on mobile. Note that .container-fluid was re-introduced in 3.1.

Full width on mobile/tablet, 1/4 screen on desktop

<div class="container-fluid"> <!-- Adds 15px left/right padding --> 
  <div class="row"> <!-- Adds -15px left/right margins -->
    <div class="col-md-4 col-md-offset-4" style="padding-left: 0, padding-right: 0"> <!-- col classes adds 15px padding, so remove the same amount -->
      <!-- Full-width for mobile -->
      <!-- 1/4 screen width for desktop -->
    </div>
  </div>
</div>

Full width on all resolutions (mobile, table, desktop)

<div class="container-fluid"> <!-- Adds 15px left/right padding -->
  <div class="row"> <!-- Adds -15px left/right margins -->
    <div>
      <!-- Full-width content -->
    </div>
  </div>
</div>

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

How to change button text or link text in JavaScript?

document.getElementById(button_id).innerHTML = 'Lock';

IF - ELSE IF - ELSE Structure in Excel

When FIND returns #VALUE!, it is an error, not a string, so you can't compare FIND(...) with "#VALUE!", you need to check if FIND returns an error with ISERROR. Also FIND can work on multiple characters.

So a simplified and working version of your formula would be:

=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))

Or, to remove the double negations:

=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")

Selenium Webdriver move mouse to Point

I am using JavaScript but some of the principles are common I am sure.

The code I am using is as follows:

    var s = new webdriver.ActionSequence(d);
    d.findElement(By.className('fc-time')).then(function(result){
        s.mouseMove(result,l).click().perform();
    });

the driver = d. The location = l is simply {x:300,y:500) - it is just an offset.

What I found during my testing was that I could not make it work without using the method to find an existing element first, using that at a basis from where to locate my click.

I suspect the figures in the locate are a bit more difficult to predict than I thought.

It is an old post but this response may help other newcomers like me.

How to add element to C++ array?

If you are writing in C++ -- it is a way better to use data structures from standard library such as vector.

C-style arrays are very error-prone, and should be avoided whenever possible.

Rails - controller action name to string

mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.

found out it's possible with self.current_method

easily found at http://www.ruby-forum.com/topic/75258

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

You also can do this directly on Frames

In [104]: df = DataFrame(dict(A = True, B = False),index=range(3))

In [105]: df
Out[105]: 
      A      B
0  True  False
1  True  False
2  True  False

In [106]: df.dtypes
Out[106]: 
A    bool
B    bool
dtype: object

In [107]: df.astype(int)
Out[107]: 
   A  B
0  1  0
1  1  0
2  1  0

In [108]: df.astype(int).dtypes
Out[108]: 
A    int64
B    int64
dtype: object

Testing if a list of integer is odd or even

You could try using Linq to project the list:

var output = lst.Select(x => x % 2 == 0).ToList();

This will return a new list of bools such that {1, 2, 3, 4, 5} will map to {false, true, false, true, false}.

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

Simply by adding below text in the httpd.conf file will solve this issue.

Header set Access-Control-Allow-Origin "*"

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

How to stop asynctask thread in android?

I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:

volatile boolean running;

public void onActivityCreated (Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


public void onDestroy() {
    super.onDestroy();

    running=false;
    ...
}

Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.

Return multiple fields as a record in PostgreSQL with PL/pgSQL

you can do this using OUT parameter and CROSS JOIN

CREATE OR REPLACE FUNCTION get_object_fields(my_name text, OUT f1 text, OUT f2 text)
AS $$
SELECT t1.name, t2.name
FROM  table1 t1 
CROSS JOIN table2 t2 
WHERE t1.name = my_name AND t2.name = my_name;
$$ LANGUAGE SQL;

then use it as a table:

select get_object_fields( 'Pending') ;
get_object_fields
-------------------
(Pending,code)
(1 row)

or

select * from get_object_fields( 'Pending');
f1    |   f
---------+---------
Pending | code
(1 row)

or

select (get_object_fields( 'Pending')).f1;
f1
---------
Pending
(1 row)

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

Trying to get property of non-object - Laravel 5

REASON WHY THIS HAPPENS (EXPLANATION)

suppose we have 2 tables users and subscription.

1 user has 1 subscription

IN USER MODEL, we have

public function subscription()
{
    return $this->hasOne('App\Subscription','user_id');
}

we can access subscription details as follows

$users = User:all();

foreach($users as $user){
    echo $user->subscription;
}

if any of the user does not have a subscription, which can be a case. we cannot use arrow function further after subscription like below

$user->subscription->abc   [this will not work] 
$user->subscription['abc']  [this will work]

but if the user has a subscription

$user->subscription->abc   [this will work] 

NOTE: try putting a if condition like this

if($user->subscription){
 return $user->subscription->abc;
}

Make index.html default, but allow index.php to be visited if typed in

RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php%{QUERY_STRING} [L]

Put these two lines at the top of your .htaccess file. It will show .html in the URL for your .php pages.

RewriteEngine on
RewriteRule ^(.*)\.php$ $1.html%{QUERY_STRING} [L]

Use this for showing .php in URL for your .html pages.

Windows Application has stopped working :: Event Name CLR20r3

Make sure the client computer has the same or higher version of the .NET framework that you built your program to.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

For my case link did NOT work as follow

ln -s /usr/bin/nodejs /usr/bin/node

But you can open /usr/local/bin/lessc as root, and change the first line from node to nodejs.

-#!/usr/bin/env node

+#!/usr/bin/env nodejs

CSS list-style-image size

I'm using:

_x000D_
_x000D_
li {_x000D_
 margin: 0;_x000D_
 padding: 36px 0 36px 84px;_x000D_
 list-style: none;_x000D_
 background-image: url("../../images/checked_red.svg");_x000D_
 background-repeat: no-repeat;_x000D_
 background-position: left center;_x000D_
 background-size: 40px;_x000D_
}
_x000D_
_x000D_
_x000D_

where background-size set the background image size.

set dropdown value by text using jquery

$("#HowYouKnow option:eq(XXX)").attr('selected', 'selected');

where XXX is the index of the one you want.

How to drop all tables from the database with manage.py CLI in Django?

I would recommend you to install django-extensions and use python manage.py reset_db command. It does exactly what you want.

How do I generate a list with a specified increment step?

Executing seq(1, 10, 1) does what 1:10 does. You can change the last parameter of seq, i.e. by, to be the step of whatever size you like.

> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability 
> [1]  0  2  4  6  8 10

How to remove all characters after a specific character in python?

The method find will return the character position in a string. Then, if you want remove every thing from the character, do this:

mystring = "123?567"
mystring[ 0 : mystring.index("?")]

>> '123'

If you want to keep the character, add 1 to the character position.

How to get current time in python and break up into year, month, day, hour, minute?

You can use gmtime

from time import gmtime

detailed_time = gmtime() 
#returns a struct_time object for current time

year = detailed_time.tm_year
month = detailed_time.tm_mon
day = detailed_time.tm_mday
hour = detailed_time.tm_hour
minute = detailed_time.tm_min

Note: A time stamp can be passed to gmtime, default is current time as returned by time()

eg.
gmtime(1521174681)

See struct_time

SQL grammar for SELECT MIN(DATE)

To get the titles for dates greater than a week ago today, use this:

SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

There's a bit of confusion in your question:

  • a Date datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE into a Date.
  • When you want to display a date, either on screen or to send it to another system via a character API (XML, file...), you use the TO_CHAR function. In Oracle, a Date has no format: it is a point in time.
  • Reciprocally, you would use TO_TIMESTAMP_TZ to convert a VARCHAR2 to a TIMESTAMP, but this won't convert a Date to a TIMESTAMP.
  • You use FROM_TZ to add the time zone information to a TIMESTAMP (or a Date).
  • In Oracle, CST is a time zone but CDT is not. CDT is a daylight saving information.
  • To complicate things further, CST/CDT (-05:00) and CST/CST (-06:00) will have different values obviously, but the time zone CST will inherit the daylight saving information depending upon the date by default.

So your conversion may not be as simple as it looks.

Assuming that you want to convert a Date d that you know is valid at time zone CST/CST to the equivalent at time zone CST/CDT, you would use:

SQL> SELECT from_tz(d, '-06:00') initial_ts,
  2         from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
  3    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  4                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  5            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00

My default timestamp format has been used here. I can specify a format explicitely:

SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
  2         to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
  3                 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
  4    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  5                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  6            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00      2012-10-09 02:10:21 -05:00

How do I iterate over an NSArray?

Add each method in your NSArray category, you gonna need it a lot

Code taken from ObjectiveSugar

- (void)each:(void (^)(id object))block {
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        block(obj);
    }];
}

How can I include css files using node, express, and ejs?

the order of registering routes is important . register 404 routes after static files.

correct order:

app.use("/admin", admin);
...

app.use(express.static(join(__dirname, "public")));

app.use((req, res) => {
  res.status(404);
  res.send("404");
});

otherwise everything which is not in routes , like css files etc.. , will become 404 .

I lose my data when the container exits

You might want to look at docker volumes if you you want to persist the data in your container. Visit https://docs.docker.com/engine/tutorials/dockervolumes/. The docker documentation is a very good place to start

generate random double numbers in c++

If accuracy is an issue here you can create random numbers with a finer graduation by randomizing the significant bits. Let's assume we want to have a double between 0.0 and 1000.0.

On MSVC (12 / Win32) RAND_MAX is 32767 for example.

If you use the common rand()/RAND_MAX scheme your gaps will be as large as

1.0 / 32767.0 * ( 1000.0 - 0.0) = 0.0305 ...

In case of IEE 754 double variables (53 significant bits) and 53 bit randomization the smallest possible randomization gap for the 0 to 1000 problem will be

2^-53 * (1000.0 - 0.0) = 1.110e-13

and therefore significantly lower.

The downside is that 4 rand() calls will be needed to obtain the randomized integral number (assuming a 15 bit RNG).

double random_range (double const range_min, double const range_max)
{
  static unsigned long long const mant_mask53(9007199254740991);
  static double const i_to_d53(1.0/9007199254740992.0);
  unsigned long long const r( (unsigned long long(rand()) | (unsigned long long(rand()) << 15) | (unsigned long long(rand()) << 30) | (unsigned long long(rand()) << 45)) & mant_mask53 );
  return range_min + i_to_d53*double(r)*(range_max-range_min);
}

If the number of bits for the mantissa or the RNG is unknown the respective values need to be obtained within the function.

#include <limits>
using namespace std;
double random_range_p (double const range_min, double const range_max)
{
  static unsigned long long const num_mant_bits(numeric_limits<double>::digits), ll_one(1), 
    mant_limit(ll_one << num_mant_bits);
  static double const i_to_d(1.0/double(mant_limit));
  static size_t num_rand_calls, rng_bits;
  if (num_rand_calls == 0 || rng_bits == 0)
  {
    size_t const rand_max(RAND_MAX), one(1);
    while (rand_max > (one << rng_bits))
    {
      ++rng_bits;
    }
    num_rand_calls = size_t(ceil(double(num_mant_bits)/double(rng_bits)));
  }
  unsigned long long r(0);
  for (size_t i=0; i<num_rand_calls; ++i)
  {
    r |= (unsigned long long(rand()) << (i*rng_bits));
  }
  r = r & (mant_limit-ll_one);
  return range_min + i_to_d*double(r)*(range_max-range_min);
}

Note: I don't know whether the number of bits for unsigned long long (64 bit) is greater than the number of double mantissa bits (53 bit for IEE 754) on all platforms or not. It would probably be "smart" to include a check like if (sizeof(unsigned long long)*8 > num_mant_bits) ... if this is not the case.

How can you find the height of text on an HTML canvas?

In normal situations the following should work:

var can = CanvasElement.getContext('2d');          //get context
var lineHeight = /[0-9]+(?=pt|px)/.exec(can.font); //get height from font variable

What is RSS and VSZ in Linux memory management

RSS is the Resident Set Size and is used to show how much memory is allocated to that process and is in RAM. It does not include memory that is swapped out. It does include memory from shared libraries as long as the pages from those libraries are actually in memory. It does include all stack and heap memory.

VSZ is the Virtual Memory Size. It includes all memory that the process can access, including memory that is swapped out, memory that is allocated, but not used, and memory that is from shared libraries.

So if process A has a 500K binary and is linked to 2500K of shared libraries, has 200K of stack/heap allocations of which 100K is actually in memory (rest is swapped or unused), and it has only actually loaded 1000K of the shared libraries and 400K of its own binary then:

RSS: 400K + 1000K + 100K = 1500K
VSZ: 500K + 2500K + 200K = 3200K

Since part of the memory is shared, many processes may use it, so if you add up all of the RSS values you can easily end up with more space than your system has.

The memory that is allocated also may not be in RSS until it is actually used by the program. So if your program allocated a bunch of memory up front, then uses it over time, you could see RSS going up and VSZ staying the same.

There is also PSS (proportional set size). This is a newer measure which tracks the shared memory as a proportion used by the current process. So if there were two processes using the same shared library from before:

PSS: 400K + (1000K/2) + 100K = 400K + 500K + 100K = 1000K

Threads all share the same address space, so the RSS, VSZ and PSS for each thread is identical to all of the other threads in the process. Use ps or top to view this information in linux/unix.

There is way more to it than this, to learn more check the following references:

Also see:

Changing the resolution of a VNC session in linux

I have a simple idea, something like this:

#!/bin/sh

echo `xrandr --current | grep current | awk '{print $8}'` >> RES1
echo `xrandr --current | grep current | awk '{print $10}'` >> RES2
cat RES2 | sed -i 's/,//g' RES2

P1RES=$(cat RES1)
P2RES=$(cat RES2)
rm RES1 RES2
echo "$P1RES"'x'"$P2RES" >> RES
RES=$(cat RES)

# Play The Game

# Finish The Game with Lower Resolution

xrandr -s $RES

Well, I need a better solution for all display devices under Linux and Similars S.O

How to convert list of numpy arrays into single numpy array?

Starting in NumPy version 1.10, we have the method stack. It can stack arrays of any dimension (all equal):

# List of arrays.
L = [np.random.randn(5,4,2,5,1,2) for i in range(10)]

# Stack them using axis=0.
M = np.stack(L)
M.shape # == (10,5,4,2,5,1,2)
np.all(M == L) # == True

M = np.stack(L, axis=1)
M.shape # == (5,10,4,2,5,1,2)
np.all(M == L) # == False (Don't Panic)

# This are all true    
np.all(M[:,0,:] == L[0]) # == True
all(np.all(M[:,i,:] == L[i]) for i in range(10)) # == True

Enjoy,

T-SQL How to select only Second row from a table?

This is also useful:

SELECT t.*
FROM (
  SELECT e1.*
    , row_number() OVER (ORDER BY e1.Rate DESC) AS _Rank
  FROM
  HumanResources.EmployeePayHistory AS e1
) AS t
WHERE t._Rank = 2

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

All of the current answers are addressing the symptom (shared memory pool exhaustion), and not the problem, which is likely not using bind variables in your sql \ JDBC queries, even when it does not seem necessary to do so. Passing queries without bind variables causes Oracle to "hard parse" the query each time, determining its plan of execution, etc.

https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:528893984337

Some snippets from the above link:

"Java supports bind variables, your developers must start using prepared statements and bind inputs into it. If you want your system to ultimately scale beyond say about 3 or 4 users -- you will do this right now (fix the code). It is not something to think about, it is something you MUST do. A side effect of this - your shared pool problems will pretty much disappear. That is the root cause. "

"The way the Oracle shared pool (a very important shared memory data structure) operates is predicated on developers using bind variables."

" Bind variables are SO MASSIVELY important -- I cannot in any way shape or form OVERSTATE their importance. "

PHP date() format when inserting into datetime in MySQL

Here's an alternative solution: if you have the date in PHP as a timestamp, bypass handling it with PHP and let the DB take care of transforming it by using the FROM_UNIXTIME function.

mysql> insert into a_table values(FROM_UNIXTIME(1231634282));
Query OK, 1 row affected (0.00 sec)

mysql> select * from a_table;

+---------------------+
| a_date              |
+---------------------+
| 2009-01-10 18:38:02 |
+---------------------+

Can I use a case/switch statement with two variables?

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

Convert List<String> to List<Integer> directly

If you're allowed to use lambdas from Java 8, you can use the following code sample.

final String text = "1:2:3:4:5";
final List<Integer> list = Arrays.asList(text.split(":")).stream()
  .map(s -> Integer.parseInt(s))
  .collect(Collectors.toList());
System.out.println(list);

No use of external libraries. Plain old new Java!

Getting the class of the element that fired an event using JQuery

If you are using jQuery 1.7:

alert($(this).prop("class"));

or:

alert($(event.target).prop("class"));

Is it possible to specify condition in Count()?

SELECT COUNT(*) FROM bla WHERE Position = 'Manager'

Unordered List (<ul>) default indent

If you don't want indention in your list and also don't care about or don't want bullets, there is the CSS-free option of using a "definition list" (HTML 4.01) or "description list" (HTML 5). Use only the non-indenting definition <dt> tags, but not the indenting description <dd> tags, neither of which produces a bullet.

<dl>
  <dt>Item 1</dt>
  <dt>Item 2</dt>
  <dt>Item 3</dt>
</dl>

The output looks like this:

Item 1
Item 2
Item 3

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

The same error and wasted 2+ hours debugging and trying all options. I was not using the Maven/POM, so I could not leverage that solution given by few.

Finally the following resolved it: Adding the jars directly to the tomcat/lib (NOT WEB-INF\lib) folder and restarting the tomcat.

How to stop a vb script running in windows

in your code, just after 'do while' statement, add this line..

`Wscript.sleep 10000`

This will let your script sleep for 10 secs and let your system take rest. Else your processor will be running this script million times a second and this will definitely load your processor.

To kill it, just goto taskmanager and kill wscript.exe or if it is not found, you will find cscript.exe, kill it pressing delete button. These would be present in process tab of your taskmanager.

Once you add that line in code, I dont think you need to kill this process. It will not load your CPU.

Have a great day.

Android 6.0 Marshmallow. Cannot write to SD Card

I faced the same problem. There are two types of permissions in Android:

  • Dangerous (access to contacts, write to external storage...)
  • Normal

Normal permissions are automatically approved by Android while dangerous permissions need to be approved by Android users.

Here is the strategy to get dangerous permissions in Android 6.0

  1. Check if you have the permission granted
  2. If your app is already granted the permission, go ahead and perform normally.
  3. If your app doesn't have the permission yet, ask for user to approve
  4. Listen to user approval in onRequestPermissionsResult

Here is my case: I need to write to external storage.

First, I check if I have the permission:

...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
    ActivityCompat.requestPermissions(parentActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
}

Then check the user's approval:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }

}

You can read more about the new permission model here: https://developer.android.com/training/permissions/requesting.html

Simple insecure two-way data "obfuscation"?

Using TripleDESCryptoServiceProvider in System.Security.Cryptography :

public static class CryptoHelper
{
    private const string Key = "MyHashString";
    private static TripleDESCryptoServiceProvider GetCryproProvider()
    {
        var md5 = new MD5CryptoServiceProvider();
        var key = md5.ComputeHash(Encoding.UTF8.GetBytes(Key));
        return new TripleDESCryptoServiceProvider() { Key = key, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 };
    }

    public static string Encrypt(string plainString)
    {
        var data = Encoding.UTF8.GetBytes(plainString);
        var tripleDes = GetCryproProvider();
        var transform = tripleDes.CreateEncryptor();
        var resultsByteArray = transform.TransformFinalBlock(data, 0, data.Length);
        return Convert.ToBase64String(resultsByteArray);
    }

    public static string Decrypt(string encryptedString)
    {
        var data = Convert.FromBase64String(encryptedString);
        var tripleDes = GetCryproProvider();
        var transform = tripleDes.CreateDecryptor();
        var resultsByteArray = transform.TransformFinalBlock(data, 0, data.Length);
        return Encoding.UTF8.GetString(resultsByteArray);
    }
}

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

It can be due to a number of reasons happening when configuring the listener. Best way is to log and see the actual error. You can do this by adding a logging.properties file to the root of your classpath with the following contents:

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

Drop primary key using script in SQL Server database

simply click

'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

Android Studio emulator does not come with Play Store for API 23

Wanted to comment on the last answer, but without login it’s only possible to make an answer:

To get rid of the "read only error" just stop the device immediately after it’s ready. My script looks as follows:

#!/bin/bash 
~/bin/AndroidSdk/tools/emulator @Nexus_6P_API_23 -no-boot-anim &
adb wait-for-device
adb shell stop
adb remount
adb push GmsCore.apk /system/priv-app
adb push GoogleServicesFramework.apk /system/priv-app
adb push GoogleLoginService.apk /system/priv-app
adb push Phonesky.apk /system/priv-app
adb shell start

select data up to a space?

select left(col, charindex(' ', col) - 1)

jQuery ui datepicker with Angularjs

onSelect doesn't work well in ng-repeat, so I made another version using event bind

html

<tr ng-repeat="product in products">
<td>
    <input type="text" ng-model="product.startDate" class="form-control date-picker" data-date-format="yyyy-mm-dd" datepicker/>
</td>
</tr>

script

angular.module('app', []).directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker();
            element.bind('blur keyup change', function(){
                var model = attrs.ngModel;
                if (model.indexOf(".") > -1) scope[model.replace(/\.[^.]*/, "")][model.replace(/[^.]*\./, "")] = element.val();
                else scope[model] = element.val();
            });
        }
    };
});

How to do a non-greedy match in grep?

The short answer is using the next regular expression:

(?s)<car .*? model=BMW .*?>.*?</car>
  • (?s) - this makes a match across multiline
  • .*? - matches any character, a number of times in a lazy way (minimal match)

A (little) more complicated answer is:

(?s)<([a-z\-_0-9]+?) .*? model=BMW .*?>.*?</\1>

This will makes possible to match car1 and car2 in the following text

<car1 ... model=BMW ...>
...
...
...
</car1>
<car2 ... model=BMW ...>
...
...
...
</car2>
  • (..) represents a capturing group
  • \1 in this context matches the sametext as most recently matched by capturing group number 1

How can I use a carriage return in a HTML tooltip?

hack but works - (tested on chrome and mobile)

just add no break spaces   till it breaks - you might have to limit the tooltip size depending on the amount of content but for small text messages this works:

&nbsp;&nbsp; etc

Tried everything above and this is the only thing that worked for me -

How do I pass variables and data from PHP to JavaScript?

As per your code

<$php
     $val = $myService->getValue(); // Makes an API and database call
     echo '<span id="value">'.$val.'</span>';
$>

Now you can get value using DOM, use innerHTML of span id, in this case you don't need to do any call to server, or Ajax or another thing.

Your page will print it using PHP, and you JavaScript will get value using DOM.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

when reimporting your keys from the old keyring, you need to specify the command:

gpg --allow-secret-key-import --import <keyring>

otherwise it will only import the public keys, not the private keys.

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Simply replace image/jpeg with application/octet-stream. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.

A simple JavaScript solution would be:

//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element, 

Another method is to use a blob: URI:

var img = document.images[0];
img.onclick = function() {
    // atob to base64_decode the data-URI
    var image_data = atob(img.src.split(',')[1]);
    // Use typed arrays to convert the binary data to a Blob
    var arraybuffer = new ArrayBuffer(image_data.length);
    var view = new Uint8Array(arraybuffer);
    for (var i=0; i<image_data.length; i++) {
        view[i] = image_data.charCodeAt(i) & 0xff;
    }
    try {
        // This is the recommended method:
        var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
    } catch (e) {
        // The BlobBuilder API has been deprecated in favour of Blob, but older
        // browsers don't know about the Blob constructor
        // IE10 also supports BlobBuilder, but since the `Blob` constructor
        //  also works, there's no need to add `MSBlobBuilder`.
        var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
        bb.append(arraybuffer);
        var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
    }

    // Use the URL object to create a temporary URL
    var url = (window.webkitURL || window.URL).createObjectURL(blob);
    location.href = url; // <-- Download!
};

Relevant documentation

load external URL into modal jquery ui dialog

_x000D_
_x000D_
if you are using **Bootstrap** this is solution, _x000D_
_x000D_
$(document).ready(function(e) {_x000D_
    $('.bootpopup').click(function(){_x000D_
  var frametarget = $(this).attr('href');_x000D_
  targetmodal = '#myModal'; _x000D_
        $('#modeliframe').attr("src", frametarget );   _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
<!-- Button trigger modal -->_x000D_
<a  href="http://twitter.github.io/bootstrap/" title="Edit Transaction" class="btn btn-primary btn-lg bootpopup" data-toggle="modal" data-target="#myModal">_x000D_
  Launch demo modal_x000D_
</a>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
         <iframe src="" id="modeliframe" style="zoom:0.60" frameborder="0" height="250" width="99.6%"></iframe>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to install Guest addition in Mac OS as guest and Windows machine as host

I've the same problem, and by the "trial and error" method I have the steps to install the guest additions on a MacOS guest:

  1. insert the guest additions cd
  2. open the cd on file manager
  3. double click on VBoxDarwinAdditions.pkg
  4. the installer opens, then click contine
  5. next screen to set location of installed files, only press install
  6. your password can be asked a couple of time while installing, write it and continue
  7. this is the tricky part, on my installation, macos show an message about the driver created by oracle won't be installed because a security issue, it has the option to enable it, so click on the button to open security screen and click on the allow button next to the oracle software listed at bottom of the security settings window, it will ask your password again. Meanwhile the pkg installer continued as if it has permissions and will say "install finished", but I don't believe it so, once I unlocked the oracle drivers installations I repeat the whole process from step 3, and in the second round all installs without asking more than the first password to install.

And it is done!

Repository access denied. access via a deployment key is read-only

Two step process to be able to push pull
Step1: Generate ssh key(public and private) on mac

Step2: Put private key in mac and public key in git website

below detailed steps are for mac users

Step 1: Generating keys

  1. (make sure you have git installed)https://git-scm.com/download/mac
  2. open terminal and type ssh-keygen this will prompt you to enter storage location for key, you may type /Users/[machinename]/.ssh/[keyname]
  3. Next it will ask for passphrase, you can either leave it blank by pressing enter or enter some keyword to be entered again at next prompt
  4. This will have created two keys for you, private and public, with name [keyname] and [keyname].pub

Step2:pushing keys to appropriate locations[mac and remote accounts i.e Github, bitbucket, gitlab etc ]

  1. Type ssh-add -K ~/.ssh/[keyname] in terminal to add your private key to the mac
  2. Type pbcopy < ~/.ssh/[keyname].pub to copy public key to clipboard
  3. Open account settings on your respective git website and go to add key, there paste the public key copied above

Done, now you can push pull.

Difference between virtual and abstract methods

Abstract Method:

  • If an abstract method is defined in a class, then the class should declare as an abstract class.

  • An abstract method should contain only method definition, should not Contain the method body/implementation.

  • An abstract method must be over ride in the derived class.

Virtual Method:

  • Virtual methods can be over ride in the derived class but not mandatory.
  • Virtual methods must have the method body/implementation along with the definition.

Example:

public abstract class baseclass
        {
            public abstract decimal getarea(decimal Radius);

            public virtual decimal interestpermonth(decimal amount)
            {
                return amount*12/100;
            }

            public virtual decimal totalamount(decimal Amount,decimal principleAmount)
            {
                return Amount + principleAmount;
            }
        }

        public class derivedclass:baseclass
        {
            public override decimal getarea(decimal Radius)
            {
                return 2 * (22 / 7) * Radius;
            }

            public override decimal interestpermonth(decimal amount)
            {
                return amount * 14 / 100;
            }
        }

SQL query, store result of SELECT in local variable

You can create table variables:

DECLARE @result1 TABLE (a INT, b INT, c INT)

INSERT INTO @result1
SELECT a, b, c
FROM table1

SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1

This should be fine for what you need.

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

Clang vs GCC - which produces faster binaries?

Here are some up-to-date albeit narrow findings of mine with GCC 4.7.2 and Clang 3.2 for C++.

UPDATE: GCC 4.8.1 v clang 3.3 comparison appended below.

UPDATE: GCC 4.8.2 v clang 3.4 comparison is appended to that.

I maintain an OSS tool that is built for Linux with both GCC and Clang, and with Microsoft's compiler for Windows. The tool, coan, is a preprocessor and analyser of C/C++ source files and codelines of such: its computational profile majors on recursive-descent parsing and file-handling. The development branch (to which these results pertain) comprises at present around 11K LOC in about 90 files. It is coded, now, in C++ that is rich in polymorphism and templates and but is still mired in many patches by its not-so-distant past in hacked-together C. Move semantics are not expressly exploited. It is single-threaded. I have devoted no serious effort to optimizing it, while the "architecture" remains so largely ToDo.

I employed Clang prior to 3.2 only as an experimental compiler because, despite its superior compilation speed and diagnostics, its C++11 standard support lagged the contemporary GCC version in the respects exercised by coan. With 3.2, this gap has been closed.

My Linux test harness for current coan development processes roughly 70K sources files in a mixture of one-file parser test-cases, stress tests consuming 1000s of files and scenario tests consuming < 1K files. As well as reporting the test results, the harness accumulates and displays the totals of files consumed and the run time consumed in coan (it just passes each coan command line to the Linux time command and captures and adds up the reported numbers). The timings are flattered by the fact that any number of tests which take 0 measurable time will all add up to 0, but the contribution of such tests is negligible. The timing stats are displayed at the end of make check like this:

coan_test_timer: info: coan processed 70844 input_files.
coan_test_timer: info: run time in coan: 16.4 secs.
coan_test_timer: info: Average processing time per input file: 0.000231 secs.

I compared the test harness performance as between GCC 4.7.2 and Clang 3.2, all things being equal except the compilers. As of Clang 3.2, I no longer require any preprocessor differentiation between code tracts that GCC will compile and Clang alternatives. I built to the same C++ library (GCC's) in each case and ran all the comparisons consecutively in the same terminal session.

The default optimization level for my release build is -O2. I also successfully tested builds at -O3. I tested each configuration 3 times back-to-back and averaged the 3 outcomes, with the following results. The number in a data-cell is the average number of microseconds consumed by the coan executable to process each of the ~70K input files (read, parse and write output and diagnostics).

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 231 | 237 |0.97 |
----------|-----|-----|-----|
Clang-3.2 | 234 | 186 |1.25 |
----------|-----|-----|------
GCC/Clang |0.99 | 1.27|

Any particular application is very likely to have traits that play unfairly to a compiler's strengths or weaknesses. Rigorous benchmarking employs diverse applications. With that well in mind, the noteworthy features of these data are:

  1. -O3 optimization was marginally detrimental to GCC
  2. -O3 optimization was importantly beneficial to Clang
  3. At -O2 optimization, GCC was faster than Clang by just a whisker
  4. At -O3 optimization, Clang was importantly faster than GCC.

A further interesting comparison of the two compilers emerged by accident shortly after those findings. Coan liberally employs smart pointers and one such is heavily exercised in the file handling. This particular smart-pointer type had been typedef'd in prior releases for the sake of compiler-differentiation, to be an std::unique_ptr<X> if the configured compiler had sufficiently mature support for its usage as that, and otherwise an std::shared_ptr<X>. The bias to std::unique_ptr was foolish, since these pointers were in fact transferred around, but std::unique_ptr looked like the fitter option for replacing std::auto_ptr at a point when the C++11 variants were novel to me.

In the course of experimental builds to gauge Clang 3.2's continued need for this and similar differentiation, I inadvertently built std::shared_ptr<X> when I had intended to build std::unique_ptr<X>, and was surprised to observe that the resulting executable, with default -O2 optimization, was the fastest I had seen, sometimes achieving 184 msecs. per input file. With this one change to the source code, the corresponding results were these;

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 234 | 234 |1.00 |
----------|-----|-----|-----|
Clang-3.2 | 188 | 187 |1.00 |
----------|-----|-----|------
GCC/Clang |1.24 |1.25 |

The points of note here are:

  1. Neither compiler now benefits at all from -O3 optimization.
  2. Clang beats GCC just as importantly at each level of optimization.
  3. GCC's performance is only marginally affected by the smart-pointer type change.
  4. Clang's -O2 performance is importantly affected by the smart-pointer type change.

Before and after the smart-pointer type change, Clang is able to build a substantially faster coan executable at -O3 optimisation, and it can build an equally faster executable at -O2 and -O3 when that pointer-type is the best one - std::shared_ptr<X> - for the job.

An obvious question that I am not competent to comment upon is why Clang should be able to find a 25% -O2 speed-up in my application when a heavily used smart-pointer-type is changed from unique to shared, while GCC is indifferent to the same change. Nor do I know whether I should cheer or boo the discovery that Clang's -O2 optimization harbours such huge sensitivity to the wisdom of my smart-pointer choices.

UPDATE: GCC 4.8.1 v clang 3.3

The corresponding results now are:

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.1 | 442 | 443 |1.00 |
----------|-----|-----|-----|
Clang-3.3 | 374 | 370 |1.01 |
----------|-----|-----|------
GCC/Clang |1.18 |1.20 |

The fact that all four executables now take a much greater average time than previously to process 1 file does not reflect on the latest compilers' performance. It is due to the fact that the later development branch of the test application has taken on lot of parsing sophistication in the meantime and pays for it in speed. Only the ratios are significant.

The points of note now are not arrestingly novel:

  • GCC is indifferent to -O3 optimization
  • clang benefits very marginally from -O3 optimization
  • clang beats GCC by a similarly important margin at each level of optimization.

Comparing these results with those for GCC 4.7.2 and clang 3.2, it stands out that GCC has clawed back about a quarter of clang's lead at each optimization level. But since the test application has been heavily developed in the meantime one cannot confidently attribute this to a catch-up in GCC's code-generation. (This time, I have noted the application snapshot from which the timings were obtained and can use it again.)

UPDATE: GCC 4.8.2 v clang 3.4

I finished the update for GCC 4.8.1 v Clang 3.3 saying that I would stick to the same coan snaphot for further updates. But I decided instead to test on that snapshot (rev. 301) and on the latest development snapshot I have that passes its test suite (rev. 619). This gives the results a bit of longitude, and I had another motive:

My original posting noted that I had devoted no effort to optimizing coan for speed. This was still the case as of rev. 301. However, after I had built the timing apparatus into the coan test harness, every time I ran the test suite the performance impact of the latest changes stared me in the face. I saw that it was often surprisingly big and that the trend was more steeply negative than I felt to be merited by gains in functionality.

By rev. 308 the average processing time per input file in the test suite had well more than doubled since the first posting here. At that point I made a U-turn on my 10 year policy of not bothering about performance. In the intensive spate of revisions up to 619 performance was always a consideration and a large number of them went purely to rewriting key load-bearers on fundamentally faster lines (though without using any non-standard compiler features to do so). It would be interesting to see each compiler's reaction to this U-turn,

Here is the now familiar timings matrix for the latest two compilers' builds of rev.301:

coan - rev.301 results

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 428 | 428 |1.00 |
----------|-----|-----|-----|
Clang-3.4 | 390 | 365 |1.07 |
----------|-----|-----|------
GCC/Clang | 1.1 | 1.17|

The story here is only marginally changed from GCC-4.8.1 and Clang-3.3. GCC's showing is a trifle better. Clang's is a trifle worse. Noise could well account for this. Clang still comes out ahead by -O2 and -O3 margins that wouldn't matter in most applications but would matter to quite a few.

And here is the matrix for rev. 619.

coan - rev.619 results

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 210 | 208 |1.01 |
----------|-----|-----|-----|
Clang-3.4 | 252 | 250 |1.01 |
----------|-----|-----|------
GCC/Clang |0.83 | 0.83|

Taking the 301 and the 619 figures side by side, several points speak out.

  • I was aiming to write faster code, and both compilers emphatically vindicate my efforts. But:

  • GCC repays those efforts far more generously than Clang. At -O2 optimization Clang's 619 build is 46% faster than its 301 build: at -O3 Clang's improvement is 31%. Good, but at each optimization level GCC's 619 build is more than twice as fast as its 301.

  • GCC more than reverses Clang's former superiority. And at each optimization level GCC now beats Clang by 17%.

  • Clang's ability in the 301 build to get more leverage than GCC from -O3 optimization is gone in the 619 build. Neither compiler gains meaningfully from -O3.

I was sufficiently surprised by this reversal of fortunes that I suspected I might have accidentally made a sluggish build of clang 3.4 itself (since I built it from source). So I re-ran the 619 test with my distro's stock Clang 3.3. The results were practically the same as for 3.4.

So as regards reaction to the U-turn: On the numbers here, Clang has done much better than GCC at at wringing speed out of my C++ code when I was giving it no help. When I put my mind to helping, GCC did a much better job than Clang.

I don't elevate that observation into a principle, but I take the lesson that "Which compiler produces the better binaries?" is a question that, even if you specify the test suite to which the answer shall be relative, still is not a clear-cut matter of just timing the binaries.

Is your better binary the fastest binary, or is it the one that best compensates for cheaply crafted code? Or best compensates for expensively crafted code that prioritizes maintainability and reuse over speed? It depends on the nature and relative weights of your motives for producing the binary, and of the constraints under which you do so.

And in any case, if you deeply care about building "the best" binaries then you had better keep checking how successive iterations of compilers deliver on your idea of "the best" over successive iterations of your code.

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

Just correct Google play services dependencies:

You are including all play services in your project. Only add those you want.

For example , if you are using only maps and g+ signin, than change

 compile 'com.google.android.gms:play-services:8.1.0'

to

compile 'com.google.android.gms:play-services-maps:8.1.0'
compile 'com.google.android.gms:play-services-plus:8.1.0'

From the doc :

In versions of Google Play services prior to 6.5, you had to compile the entire package of APIs into your app. In some cases, doing so made it more difficult to keep the number of methods in your app (including framework APIs, library methods, and your own code) under the 65,536 limit.

From version 6.5, you can instead selectively compile Google Play service APIs into your app. For example, to include only the Google Fit and Android Wear APIs, replace the following line in your build.gradle file:
compile 'com.google.android.gms:play-services:8.3.0'
with these lines:

compile 'com.google.android.gms:play-services-fitness:8.3.0'
compile 'com.google.android.gms:play-services-wearable:8.3.0'

Whole list can be found here.

How can I get System variable value in Java?

Are you on a linux system? If so be sure you are exporting your variable.

myVar=testvalue; export myVar

I get null unless I use export to define the value globally.

How to access global variables

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

show loading icon until the page is load?

Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.

<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
    jQuery("#" + id).html(jQuery("#loading").html());
    jQuery("#" + id).show();
}

In Git, what is the difference between origin/master vs origin master?

Given the fact that you can switch to origin/master (though in detached state) while having your network cable unplugged, it must be a local representation of the master branch at origin.

Multiple simultaneous downloads using Wget?

use

aria2c -x 10 -i websites.txt >/dev/null 2>/dev/null &

in websites.txt put 1 url per line, example:

https://www.example.com/1.mp4
https://www.example.com/2.mp4
https://www.example.com/3.mp4
https://www.example.com/4.mp4
https://www.example.com/5.mp4

Hibernate table not mapped error in HQL query

Ensure your have set the table name on the entity annotation too.

@Entity(name = "table_name")
@Table(name = "table_name")
public class TableName {

}

jQuery get the rendered height of an element?

Hm we can get the Element geometry...

var geometry;
geometry={};
var element=document.getElementById(#ibims);
var rect = element.getBoundingClientRect();
this.geometry.top=rect.top;
this.geometry.right=rect.right;
this.geometry.bottom=rect.bottom;
this.geometry.left=rect.left;
this.geometry.height=this.geometry.bottom-this.geometry.top;
this.geometry.width=this.geometry.right-this.geometry.left;
console.log(this.geometry);

How about this plain JS ?

How can I add an item to a ListBox in C# and WinForms?

If you are adding integers, as you say in your question, this will add 50 (from 1 to 50):

for (int x = 1; x <= 50; x++)
{
   list.Items.Add(x);
}

You do not need to set DisplayMember and ValueMember unless you are adding objects that have specific properties that you want to display to the user. In your example:

listbox1.Items.Add(new { clan = "Foo", sifOsoba = 1234 });

Failed to build gem native extension (installing Compass)

On Mac OS you need to install this feature!

xcode-select --install

How to import the class within the same directory or sub directory?

I'm not sure why this work but using Pycharm build from file_in_same_dir import class_name

The IDE complained about it but it seems it still worked. I'm using Python 3.7

Dynamically add child components in React

First, I wouldn't use document.body. Instead add an empty container:

index.html:

<html>
    <head></head>
    <body>
        <div id="app"></div>
    </body>
</html>

Then opt to only render your <App /> element:

main.js:

var App = require('./App.js');
ReactDOM.render(<App />, document.getElementById('app'));

Within App.js you can import your other components and ignore your DOM render code completely:

App.js:

var SampleComponent = require('./SampleComponent.js');

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component!</h1>
                <SampleComponent name="SomeName" />
            </div>
        );
    }
});

SampleComponent.js:

var SampleComponent = React.createClass({
    render: function() {
        return (
            <div>
                <h1>Sample Component!</h1>
            </div>
        );
    }
});

Then you can programmatically interact with any number of components by importing them into the necessary component files using require.

How to set env variable in Jupyter notebook

To set an env variable in a jupyter notebook, just use a % magic commands, either %env or %set_env, e.g., %env MY_VAR=MY_VALUE or %env MY_VAR MY_VALUE. (Use %env by itself to print out current environmental variables.)

See: http://ipython.readthedocs.io/en/stable/interactive/magics.html

Reactjs convert html string to jsx

npm i html-react-parser;

import Parser from 'html-react-parser';

<td>{Parser(this.state.archyves)}</td>

Easiest way to flip a boolean value?

You can flip a value like so:

myVal = !myVal;

so your code would shorten down to:

switch(wParam) {
    case VK_F11:
    flipVal = !flipVal;
    break;

    case VK_F12:
    otherVal = !otherVal;
    break;

    default:
    break;
}

Android: long click on a button -> perform actions

To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:

    image = (ImageView) findViewById(R.id.imageViewCompass);
    image.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            shortclick();
        }
     });

    image.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        longclick();
        return true;
    }
});

//Then the functions that are called:

 public void shortclick()
{
 Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();

}

 public void longclick()
{
 Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();

}

It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.

Gradients in Internet Explorer 9

The code I use for all browser gradients:

background: #0A284B;
background: -webkit-gradient(linear, left top, left bottom, from(#0A284B), to(#135887));
background: -webkit-linear-gradient(#0A284B, #135887);
background: -moz-linear-gradient(top, #0A284B, #135887);
background: -ms-linear-gradient(#0A284B, #135887);
background: -o-linear-gradient(#0A284B, #135887);
background: linear-gradient(#0A284B, #135887);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0A284B', endColorstr='#135887');
zoom: 1;

You will need to specify a height or zoom: 1 to apply hasLayout to the element for this to work in IE.


Update:

Here is a LESS Mixin (CSS) version for all you LESS users out there:

.gradient(@start, @end) {
    background: mix(@start, @end, 50%);
    filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorStr="@start~", EndColorStr="@end~")";
    background: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end));
    background: -webkit-linear-gradient(@start, @end);
    background: -moz-linear-gradient(top, @start, @end);
    background: -ms-linear-gradient(@start, @end);
    background: -o-linear-gradient(@start, @end);
    background: linear-gradient(@start, @end);
    zoom: 1;
}

What's the best way to join on the same table twice?

First, I would try and refactor these tables to get away from using phone numbers as natural keys. I am not a fan of natural keys and this is a great example why. Natural keys, especially things like phone numbers, can change and frequently so. Updating your database when that change happens will be a HUGE, error-prone headache. *

Method 1 as you describe it is your best bet though. It looks a bit terse due to the naming scheme and the short aliases but... aliasing is your friend when it comes to joining the same table multiple times or using subqueries etc.

I would just clean things up a bit:

SELECT t.PhoneNumber1, t.PhoneNumber2, 
   t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2
FROM Table1 t
JOIN Table2 t1 ON t1.PhoneNumber = t.PhoneNumber1
JOIN Table2 t2 ON t2.PhoneNumber = t.PhoneNumber2

What i did:

  • No need to specify INNER - it's implied by the fact that you don't specify LEFT or RIGHT
  • Don't n-suffix your primary lookup table
  • N-Suffix the table aliases that you will use multiple times to make it obvious

*One way DBAs avoid the headaches of updating natural keys is to not specify primary keys and foreign key constraints which further compounds the issues with poor db design. I've actually seen this more often than not.

How to select from subquery using Laravel Query Builder?

Correct way described in this answer: https://stackoverflow.com/a/52772444/2519714 Most popular answer at current moment is not totally correct.

This way https://stackoverflow.com/a/24838367/2519714 is not correct in some cases like: sub select has where bindings, then joining table to sub select, then other wheres added to all query. For example query: select * from (select * from t1 where col1 = ?) join t2 on col1 = col2 and col3 = ? where t2.col4 = ? To make this query you will write code like:

$subQuery = DB::query()->from('t1')->where('t1.col1', 'val1');
$query = DB::query()->from(DB::raw('('. $subQuery->toSql() . ') AS subquery'))
    ->mergeBindings($subQuery->getBindings());
$query->join('t2', function(JoinClause $join) {
    $join->on('subquery.col1', 't2.col2');
    $join->where('t2.col3', 'val3');
})->where('t2.col4', 'val4');

During executing this query, his method $query->getBindings() will return bindings in incorrect order like ['val3', 'val1', 'val4'] in this case instead correct ['val1', 'val3', 'val4'] for raw sql described above.

One more time correct way to do this:

$subQuery = DB::query()->from('t1')->where('t1.col1', 'val1');
$query = DB::query()->fromSub($subQuery, 'subquery');
$query->join('t2', function(JoinClause $join) {
    $join->on('subquery.col1', 't2.col2');
    $join->where('t2.col3', 'val3');
})->where('t2.col4', 'val4');

Also bindings will be automatically and correctly merged to new query.

How to show a confirm message before delete?

For "confirmation message on delete" use:

                       $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "Searching.aspx/Delete_Student_Data",
                        data: "{'StudentID': '" + studentID + "'}",
                        dataType: "json",
                        success: function (data) {
                            alert("Delete StudentID Successfully");
                            return true;
                        }

Accessing localhost:port from Android emulator

I solved it with the installation of "Conveyor by Keyoti" in Visual Studio Professional 2015. Conveyor generate a REMOTE address (your IP) with a port (45455) that enable external request. Example:

enter image description here

Conveyor allows you test web applications from from external tablets and phones on your network or from Android emulators (without http://10.0.2.2:<hostport>)

The steps are in the following link :

https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti

Liquibase lock - reasons?

Sometimes if the update application is abruptly stopped, then the lock remains stuck.

Then running

UPDATE DATABASECHANGELOGLOCK SET LOCKED=0, LOCKGRANTED=null, LOCKEDBY=null where ID=1;

against the database helps.

You may also need to replace LOCKED=0 with LOCKED=FALSE.

Or you can simply drop the DATABASECHANGELOGLOCK table, it will be recreated.

Ajax using https on an http page

You could attempt to load the the https page in an iframe and route all ajax requests in/out of the frame via some bridge, it's a hackaround but it might work (not sure if it will impose the same access restrictions given the secure context). Otherwise a local http proxy to reroute requests (like any cross domain calls) would be the accepted solution.