Programs & Examples On #Synchronisation

Function to convert column number to letter?

this is only for REFEDIT ... generaly use uphere code shortly version... easy to be read and understood / it use poz of $

Private Sub RefEdit1_Change()

    Me.Label1.Caption = NOtoLETTER(RefEdit1.Value) ' you may assign to a variable  var=....'

End Sub

Function NOtoLETTER(REFedit)

    Dim First As Long, Second As Long

    First = InStr(REFedit, "$")                 'first poz of $
    Second = InStr(First + 1, REFedit, "$")     'second poz of $

    NOtoLETTER = Mid(REFedit, First + 1, Second - First - 1)   'extract COLUMN LETTER

End Function

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

Get clicked item and its position in RecyclerView

Put this code where you define recycler view in activity.

    rv_list.addOnItemTouchListener(
            new RecyclerItemClickListener(activity, new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View v, int position) {

                    Toast.makeText(activity, "" + position, Toast.LENGTH_SHORT).show();
                }
            })
    );

Then make separate class and put this code:

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    private OnItemClickListener mListener;
    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }
    GestureDetector mGestureDetector;
    public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }
        });
    }
    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

jquery clear input default value

Unless you're really worried about older browsers, you could just use the new html5 placeholder attribute like so:

<input type="text" name="email" placeholder="Email address" class="input" />

Selecting distinct values from a JSON

I would use one Object and one Array, if you want to save some cycle:

var lookup = {};
var items = json.DATA;
var result = [];

for (var item, i = 0; item = items[i++];) {
  var name = item.name;

  if (!(name in lookup)) {
    lookup[name] = 1;
    result.push(name);
  }
}

In this way you're basically avoiding the indexOf / inArray call, and you will get an Array that can be iterate quicker than iterating object's properties – also because in the second case you need to check hasOwnProperty.

Of course if you're fine with just an Object you can avoid the check and the result.push at all, and in case get the array using Object.keys(lookup), but it won't be faster than that.

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

Java: Integer equals vs. ==

As well for correctness of using == you can just unbox one of compared Integer values before doing == comparison, like:

if ( firstInteger.intValue() == secondInteger ) {..

The second will be auto unboxed (of course you have to check for nulls first).

Python "string_escape" vs "unicode_escape"

Within the range 0 = c < 128, yes the ' is the only difference for CPython 2.6.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

Outside of this range the two types are not exchangeable.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode

On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.

Http Post request with content type application/x-www-form-urlencoded not working in Spring

Remove @ResponseBody annotation from your use parameters in method. Like this;

   @Autowired
    ProjectService projectService;

    @RequestMapping(path = "/add", method = RequestMethod.POST)
    public ResponseEntity<Project> createNewProject(Project newProject){
        Project project = projectService.save(newProject);

        return new ResponseEntity<Project>(project,HttpStatus.CREATED);
    }

How to set the DefaultRoute to another Route in React Router

I ran into a similar issue; I wanted a default route handler if none of the route handler matched.

My solutions is to use a wildcard as the path value. ie Also make sure it is the last entry in your routes definition.

<Route path="/" component={App} >
    <IndexRoute component={HomePage} />
    <Route path="about" component={AboutPage} />
    <Route path="home" component={HomePage} />
    <Route path="*" component={HomePage} />
</Route>

How can I set a cookie in react?

Little update. There is a hook available for react-cookie

1) First of all, install the dependency (just for a note)

yarn add react-cookie

or

npm install react-cookie

2) My usage example:

// SignInComponent.js
import { useCookies } from 'react-cookie'

const SignInComponent = () => {

// ...

const [cookies, setCookie] = useCookies(['access_token', 'refresh_token'])

async function onSubmit(values) {
    const response = await getOauthResponse(values);

    let expires = new Date()
    expires.setTime(expires.getTime() + (response.data.expires_in * 1000))
    setCookie('access_token', response.data.access_token, { path: '/',  expires})
    setCookie('refresh_token', response.data.refresh_token, {path: '/', expires})

    // ...
}

// next goes my sign-in form

}

Hope it is helpful.

Suggestions to improve the example above are very appreciated!

How to convert a single char into an int

If you are worried about encoding, you can always use a switch statement.

Just be careful with the format you keep those large numbers in. The maximum size for an integer in some systems is as low as 65,535 (32,767 signed). Other systems, you've got 2,147,483,647 (or 4,294,967,295 unsigned)

Where can I find the TypeScript version installed in Visual Studio?

I have VS2015 and I have to run a build with TypeScript 1.7, although I have 1.8 installed via npm install typescript -g there are two ways (at least for me they worked):

  1. Go to your .proj file and add <TypeScriptToolsVersion>1.7</TypeScriptToolsVersion> as up as possible. Rebuild, re-run. If it doesn't work try 2.
  2. Go to Control Panel -> System -> Advanced System Settings -> Enviroment Variables. Make sure you add your desired TypeScript version first: C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.7;C:\Users\serban\AppData\Roaming\npm

This will also affect your CLI:

$ tsc -v
message TS6029: Version 1.7.5

Command-line tool for finding out who is locking a file

Download Handle.

https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx

If you want to find what program has a handle on a certain file, run this from the directory that Handle.exe is extracted to. Unless you've added Handle.exe to the PATH environment variable. And the file path is C:\path\path\file.txt", run this:

handle "C:\path\path\file.txt"

This will tell you what process(es) have the file (or folder) locked.

Which SchemaType in Mongoose is Best for Timestamp?

The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:

var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

This option adds createdAt and updatedAt properties that are timestamped with a Date, and which does all the work for you. Any time you update the document, it updates the updatedAt property. Schema Timestamps Docs.

SQL Server String Concatenation with Null

In Sql Server:

insert into Table_Name(PersonName,PersonEmail) values(NULL,'[email protected]')

PersonName is varchar(50), NULL is not a string, because we are not passing with in single codes, so it treat as NULL.

Code Behind:

string name = (txtName.Text=="")? NULL : "'"+ txtName.Text +"'";
string email = txtEmail.Text;

insert into Table_Name(PersonName,PersonEmail) values(name,'"+email+"')

iOS app 'The application could not be verified' only on one device

I resolved this issue by changing the Build System to legacy in xcode.

I had the same problem but the mentioned solutions above didn't work for me. Even I had no previous app on device, I got this error when deploying on my device.

How to do:

Simply, go to menu File > Project Setting, inside Share Project Settings, change Build System from "New Build System (default)" to "Lagacy Build System".

Clear and refresh jQuery Chosen dropdown list

In my case, I need to update selected value at each change because when I submit form, it always gets wrong values and I used multiple chosen drop downs. Rather than updating single entries, change selector to update all drop downs. This might help someone

 $(".chosen-select").chosen().change(function () {
    var item = $(this).val();
    $('.chosen-select').trigger('chosen:updated');
});

Get a list of all the files in a directory (recursive)

Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:

import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };

See also [1] for more examples.

[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html

Android emulator-5554 offline

Do you have bluestacks installed? If you do, the background processes that it runs creates the offline device "emulator-5554".

Go to the task manager and end all the processes with the description of "Bluestacks"

Select unique or distinct values from a list in UNIX shell script

Unique, as requested, (but not sorted);
uses fewer system resources for less than ~70 elements (as tested with time);
written to take input from stdin,
(or modify and include in another script):
(Bash)

bag2set () {
    # Reduce a_bag to a_set.
    local -i i j n=${#a_bag[@]}
    for ((i=0; i < n; i++)); do
        if [[ -n ${a_bag[i]} ]]; then
            a_set[i]=${a_bag[i]}
            a_bag[i]=$'\0'
            for ((j=i+1; j < n; j++)); do
                [[ ${a_set[i]} == ${a_bag[j]} ]] && a_bag[j]=$'\0'
            done
        fi
    done
}
declare -a a_bag=() a_set=()
stdin="$(</dev/stdin)"
declare -i i=0
for e in $stdin; do
    a_bag[i]=$e
    i=$i+1
done
bag2set
echo "${a_set[@]}"

How do I enable --enable-soap in php on linux?

As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

./configure --prefix ...

The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

I have to keep a separate virtual machine with everything installed for my recompilation purposes.

How to center a navigation bar with CSS or HTML?

If you have your navigation <ul> with class #nav Then you need to put that <ul> item within a div container. Make your div container the 100% width. and set the text-align: element to center in the div container. Then in your <ul> set that class to have 3 particular elements: text-align:center; position: relative; and display: inline-block;

that should center it.

Convert canvas to PDF

Please see https://github.com/joshua-gould/canvas2pdf. This library creates a PDF representation of your canvas element, unlike the other proposed solutions which embed an image in a PDF document.

//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();

Is it possible to specify a different ssh port when using rsync?

When calling rsync within java (and perhaps other languages), I found that setting

-e ssh -p 22

resulting in rsync complaining it could not execute the binary:

ssh -p 22

because that path ssh -p 22 did not exist (the -p and 22 are no longer arguments for some reason and now make up part of the path to the binary rsync should call).

To workaround this problem I was able to use this environment variable:

export "RSYNC_RSH=ssh -p 2222"

(Programmatically set within java using env.put("RSYNC_RSH", "ssh -p " + port);)

MVC Razor Hidden input and passing values

As you may have already figured, Asp.Net MVC is a different paradigm than Asp.Net (webforms). Accessing form elements between the server and client take a different approach in Asp.Net MVC.

You can google more reading material on this on the web. For now, I would suggest using Ajax to get or post data to the server. You can still employ input type="hidden", but initialize it with a value from the ViewData or for Razor, ViewBag.

For example, your controller may look like this:

public ActionResult Index()
{
     ViewBag.MyInitialValue = true;
     return View();
} 

In your view, you can have an input elemet that is initialized by the value in your ViewBag:

<input type="hidden" name="myHiddenInput" id="myHiddenInput" value="@ViewBag.MyInitialValue" />

Then you can pass data between the client and server via ajax. For example, using jQuery:

$.get('GetMyNewValue?oldValue=' + $('#myHiddenInput').val(), function (e) {
   // blah
});

You can alternatively use $.ajax, $.getJSON, $.post depending on your requirement.

How can I specify my .keystore file with Spring Boot and Tomcat?

For external keystores, prefix with "file:"

server.ssl.key-store=file:config/keystore 

What's the difference between JavaScript and JScript?

Javascript, the language, came first, from Netscape.

Microsoft reverse engineered Javascript and called it JScript to avoid trademark issues with Sun. (Netscape and Sun were partnered up at the time, so this was less of an issue)

The languages are identical, both are dialects of ECMA script, the after-the-fact standard.

Although the languages are identical, since JScript runs in Internet Explorer, it has access to different objects exposed by the browser (such as ActiveXObject)

How to distinguish mouse "click" and "drag"

from @Przemek 's answer,

_x000D_
_x000D_
function listenClickOnly(element, callback, threshold=10) {
  let drag = 0;
  element.addEventListener('mousedown', () => drag = 0);
  element.addEventListener('mousemove', () => drag++);
  element.addEventListener('mouseup', e => {
    if (drag<threshold) callback(e);
  });
}

listenClickOnly(
  document,
  () => console.log('click'),
  10
);
_x000D_
_x000D_
_x000D_

How to use multiprocessing queue in Python?

We implemented two versions of this, one a simple multi thread pool that can execute many types of callables, making our lives much easier and the second version that uses processes, which is less flexible in terms of callables and requires and extra call to dill.

Setting frozen_pool to true will freeze execution until finish_pool_queue is called in either class.

Thread Version:

'''
Created on Nov 4, 2019

@author: Kevin
'''
from threading import Lock, Thread
from Queue import Queue
import traceback
from helium.loaders.loader_retailers import print_info
from time import sleep
import signal
import os

class ThreadPool(object):
    def __init__(self, queue_threads, *args, **kwargs):
        self.frozen_pool = kwargs.get('frozen_pool', False)
        self.print_queue = kwargs.get('print_queue', True)
        self.pool_results = []
        self.lock = Lock()
        self.queue_threads = queue_threads
        self.queue = Queue()
        self.threads = []

        for i in range(self.queue_threads):
            t = Thread(target=self.make_pool_call)
            t.daemon = True
            t.start()
            self.threads.append(t)

    def make_pool_call(self):
        while True:
            if self.frozen_pool:
                #print '--> Queue is frozen'
                sleep(1)
                continue

            item = self.queue.get()
            if item is None:
                break

            call = item.get('call', None)
            args = item.get('args', [])
            kwargs = item.get('kwargs', {})
            keep_results = item.get('keep_results', False)

            try:
                result = call(*args, **kwargs)

                if keep_results:
                    self.lock.acquire()
                    self.pool_results.append((item, result))
                    self.lock.release()

            except Exception as e:
                self.lock.acquire()
                print e
                traceback.print_exc()
                self.lock.release()
                os.kill(os.getpid(), signal.SIGUSR1)

            self.queue.task_done()

    def finish_pool_queue(self):
        self.frozen_pool = False

        while self.queue.unfinished_tasks > 0:
            if self.print_queue:
                print_info('--> Thread pool... %s' % self.queue.unfinished_tasks)
            sleep(5)

        self.queue.join()

        for i in range(self.queue_threads):
            self.queue.put(None)

        for t in self.threads:
            t.join()

        del self.threads[:]

    def get_pool_results(self):
        return self.pool_results

    def clear_pool_results(self):
        del self.pool_results[:]

Process Version:

  '''
Created on Nov 4, 2019

@author: Kevin
'''
import traceback
from helium.loaders.loader_retailers import print_info
from time import sleep
import signal
import os
from multiprocessing import Queue, Process, Value, Array, JoinableQueue, Lock,\
    RawArray, Manager
from dill import dill
import ctypes
from helium.misc.utils import ignore_exception
from mem_top import mem_top
import gc

class ProcessPool(object):
    def __init__(self, queue_processes, *args, **kwargs):
        self.frozen_pool = Value(ctypes.c_bool, kwargs.get('frozen_pool', False))
        self.print_queue = kwargs.get('print_queue', True)
        self.manager = Manager()
        self.pool_results = self.manager.list()
        self.queue_processes = queue_processes
        self.queue = JoinableQueue()
        self.processes = []

        for i in range(self.queue_processes):
            p = Process(target=self.make_pool_call)
            p.start()
            self.processes.append(p)

        print 'Processes', self.queue_processes

    def make_pool_call(self):
        while True:
            if self.frozen_pool.value:
                sleep(1)
                continue

            item_pickled = self.queue.get()

            if item_pickled is None:
                #print '--> Ending'
                self.queue.task_done()
                break

            item = dill.loads(item_pickled)

            call = item.get('call', None)
            args = item.get('args', [])
            kwargs = item.get('kwargs', {})
            keep_results = item.get('keep_results', False)

            try:
                result = call(*args, **kwargs)

                if keep_results:
                    self.pool_results.append(dill.dumps((item, result)))
                else:
                    del call, args, kwargs, keep_results, item, result

            except Exception as e:
                print e
                traceback.print_exc()
                os.kill(os.getpid(), signal.SIGUSR1)

            self.queue.task_done()

    def finish_pool_queue(self, callable=None):
        self.frozen_pool.value = False

        while self.queue._unfinished_tasks.get_value() > 0:
            if self.print_queue:
                print_info('--> Process pool... %s' % (self.queue._unfinished_tasks.get_value()))

            if callable:
                callable()

            sleep(5)

        for i in range(self.queue_processes):
            self.queue.put(None)

        self.queue.join()
        self.queue.close()

        for p in self.processes:
            with ignore_exception: p.join(10)
            with ignore_exception: p.terminate()

        with ignore_exception: del self.processes[:]

    def get_pool_results(self):
        return self.pool_results

    def clear_pool_results(self):
        del self.pool_results[:]
def test(eg):
        print 'EG', eg

Call with either:

tp = ThreadPool(queue_threads=2)
tp.queue.put({'call': test, 'args': [random.randint(0, 100)]})
tp.finish_pool_queue()

or

pp = ProcessPool(queue_processes=2)
pp.queue.put(dill.dumps({'call': test, 'args': [random.randint(0, 100)]}))
pp.queue.put(dill.dumps({'call': test, 'args': [random.randint(0, 100)]}))
pp.finish_pool_queue()

Best place to insert the Google Analytics code

If you want your scripts to load after page has been rendered, you can use:

function getScript(a, b) {
    var c = document.createElement("script");
    c.src = a;
    var d = document.getElementsByTagName("head")[0],
        done = false;
    c.onload = c.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
            done = true;
            b();
            c.onload = c.onreadystatechange = null;
            d.removeChild(c)
        }
    };
    d.appendChild(c)
}

//call the function
getScript("http://www.google-analytics.com/ga.js", function() {
    // do stuff after the script has loaded
});

Android: How to create a Dialog without a title?

Set the title to empty string using builder.

    Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("");
...
    builder.show();

Best way to update an element in a generic List

If the list is sorted (as happens to be in the example) a binary search on index certainly works.

    public static Dog Find(List<Dog> AllDogs, string Id)
    {
        int p = 0;
        int n = AllDogs.Count;
        while (true)
        {
            int m = (n + p) / 2;
            Dog d = AllDogs[m];
            int r = string.Compare(Id, d.Id);
            if (r == 0)
                return d;
            if (m == p)
                return null;
            if (r < 0)
                n = m;
            if (r > 0)
                p = m;
        }
    }

Not sure what the LINQ version of this would be.

How to check if mod_rewrite is enabled in php?

Use this function:

function apache_module_exists($module)
{
    return in_array($module, apache_get_modules());
}

Angular IE Caching issue for $http

To avoid caching, one option is to give different URL for the same resource or data. To generate different URL, you can add a random query string to the end of the URL. This technique works for JQuery, Angular or other type ajax requests.

myURL = myURL +"?random="+new Date().getTime();

Project has no default.properties file! Edit the project properties to set one

See project.properties in android project. In ADT 14, default.properties was renamed to project.properties.

Quote from the changelog:

default.properties which is the main project’s properties file containing information such as the build platform target and the library dependencies has been renamed project.properties.

*Note: Per the above link, if you don't have a default.properties file, likely you should upgrade your tools.

See build changes in revision 14, at the bottom under "Project Setup"

Pass react component as props

As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:

https://reactjs.org/docs/composition-vs-inheritance.html

Make sure you are actually passing a component and not an object (this tripped me up initially).

The code is simply this:

const Parent = () => { 
  return (
    <Child  componentToPassDown={<SomeComp />}  />
  )
}

const Child = ({ componentToPassDown }) => { 
  return (
    <>
     {componentToPassDown}  
    </>
  )
}

How can I pause setInterval() functions?

You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value. So there is no need to pause timer and you will get best possible accuracy in this way.

"Insufficient Storage Available" even there is lot of free space in device memory

Clearing the Google Play cache memory will also help you... Go to the app information page of Google Play and clear it.

New lines inside paragraph in README.md

You can use a backslash at the end of a line.
So this:

a\
b\
c

will then look like:

a
b
c

Notice that there is no backslash at the end of the last line (after the 'c' character).

How to call jQuery function onclick?

JS

 $(function () {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
    $("#submit").click(function () {
        alert('button clicked');
    });
});

html

<input id="submit" type="submit" value="submit" name="submit">

Open images? Python

This is how to open any file:

from os import path

filepath = '...' # your path
file = open(filepath, 'r')

How to insert element into arrays at specific position?

Very simple 2 string answer to your question:

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

At first you insert anything to your third element with array_splice and then assign a value to this element:

array_splice($array_1, 3, 0 , true);
$array_1[3] = array('sample_key' => 'sample_value');

Declaration of Methods should be Compatible with Parent Methods in PHP

This message means that there are certain possible method calls which may fail at run-time. Suppose you have

class A { public function foo($a = 1) {;}}
class B extends A { public function foo($a) {;}}
function bar(A $a) {$a->foo();}

The compiler only checks the call $a->foo() against the requirements of A::foo() which requires no parameters. $a may however be an object of class B which requires a parameter and so the call would fail at runtime.

This however can never fail and does not trigger the error

class A { public function foo($a) {;}}
class B extends A { public function foo($a = 1) {;}}
function bar(A $a) {$a->foo();}

So no method may have more required parameters than its parent method.

The same message is also generated when type hints do not match, but in this case PHP is even more restrictive. This gives an error:

class A { public function foo(StdClass $a) {;}}
class B extends A { public function foo($a) {;}}

as does this:

class A { public function foo($a) {;}}
class B extends A { public function foo(StdClass $a) {;}}

That seems more restrictive than it needs to be and I assume is due to internals.

Visibility differences cause a different error, but for the same basic reason. No method can be less visible than its parent method.

How to implement reCaptcha for ASP.NET MVC?

Step 1: Client site integration

Paste this snippet before the closing </head> tag on your HTML template:

<script src='https://www.google.com/recaptcha/api.js'></script>

Paste this snippet at the end of the <form> where you want the reCAPTCHA widget to appear:

<div class="g-recaptcha" data-sitekey="your-site-key"></div>

Step 2: Server site integration

When your users submit the form where you integrated reCAPTCHA, you'll get as part of the payload a string with the name "g-recaptcha-response". In order to check whether Google has verified that user, send a POST request with these parameters:

URL : https://www.google.com/recaptcha/api/siteverify

secret : your secret key

response : The value of 'g-recaptcha-response'.

Now in action of your MVC app:

// return ActionResult if you want
    public string RecaptchaWork()
    {
        // Get recaptcha value
        var r = Request.Params["g-recaptcha-response"];
        // ... validate null or empty value if you want
        // then
        // make a request to recaptcha api
        using (var wc = new WebClient())
        {
            var validateString = string.Format(
                "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
               "your_secret_key",    // secret recaptcha key
               r); // recaptcha value
             // Get result of recaptcha
            var recaptcha_result = wc.DownloadString(validateString);
            // Just check if request make by user or bot
            if (recaptcha_result.ToLower().Contains("false"))
            {
                 return "recaptcha false";
            }
        }
        // Do your work if request send from human :)
    }

select count(*) from table of mysql in php

You need to alias the aggregate using the as keyword in order to call it from mysql_fetch_assoc

$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];

How to find the array index with a value?

Array.indexOf doesnt work in some versions of internet explorer - there are lots of alternative ways of doing it though ... see this question / answer : How do I check if an array includes an object in JavaScript?

Variably modified array at file scope

It is also possible to use enumeration.

typedef enum {
    typeNo1 = 1,
    typeNo2,
    typeNo3,
    typeNo4,
    NumOfTypes = typeNo4
}  TypeOfSomething;

Pandas "Can only compare identically-labeled DataFrame objects" error

You can also try dropping the index column if it is not needed to compare:

print(df1.reset_index(drop=True) == df2.reset_index(drop=True))

I have used this same technique in a unit test like so:

from pandas.util.testing import assert_frame_equal

assert_frame_equal(actual.reset_index(drop=True), expected.reset_index(drop=True))

Git: add vs push vs commit

  1. git add adds your modified files to the queue to be committed later. Files are not committed

  2. git commit commits the files that have been added and creates a new revision with a log... If you do not add any files, git will not commit anything. You can combine both actions with git commit -a

  3. git push pushes your changes to the remote repository.

This figure from this git cheat sheet gives a good idea of the work flow

enter image description here

git add isn't on the figure because the suggested way to commit is the combined git commit -a, but you can mentally add a git add to the change block to understand the flow.

Lastly, the reason why push is a separate command is because of git's philosophy. git is a distributed versioning system, and your local working directory is your repository! All changes you commit are instantly reflected and recorded. push is only used to update the remote repo (which you might share with others) when you're done with whatever it is that you're working on. This is a neat way to work and save changes locally (without network overhead) and update it only when you want to, instead of at every commit. This indirectly results in easier commits/branching etc (why not, right? what does it cost you?) which leads to more save points, without messing with the repository.

What does 'synchronized' mean?

What is the synchronized keyword?

Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.

Synchronized blocks or methods prevents thread interference and make sure that data is consistent. At any point of time, only one thread can access a synchronized block or method (critical section) by acquiring a lock. Other thread(s) will wait for release of lock to access critical section.

When are methods synchronized?

Methods are synchronized when you add synchronized to method definition or declaration. You can also synchronize a particular block of code with-in a method.

What does it mean pro grammatically and logically?

It means that only one thread can access critical section by acquiring a lock. Unless this thread release this lock, all other thread(s) will have to wait to acquire a lock. They don't have access to enter critical section with out acquiring lock.

This can't be done with a magic. It's programmer responsibility to identify critical section(s) in application and guard it accordingly. Java provides a framework to guard your application, but where and what all sections to be guarded is the responsibility of programmer.

More details from java documentation page

Intrinsic Locks and Synchronization:

Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.

Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them.

A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.

When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock.

Making methods synchronized has two effects:

First, it is not possible for two invocations of synchronized methods on the same object to interleave.

When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object.

This guarantees that changes to the state of the object are visible to all threads.

Look for other alternatives to synchronization in :

Avoid synchronized(this) in Java?

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

Splitting a continuous variable into equal sized groups

If you want to split into 3 equally distributed groups, the answer is the same as Ben Bolker's answer above - use ggplot2::cut_number(). For sake of completion here are the 3 methods of converting continuous to categorical (binning).

  • cut_number(): Makes n groups with (approximately) equal numbers of observation
  • cut_interval(): Makes n groups with equal range
  • cut_width(): Makes groups of width

My go-to is cut_number() because this uses evenly spaced quantiles for binning observations. Here's an example with skewed data.

library(tidyverse)

skewed_tbl <- tibble(
    counts = c(1:100, 1:50, 1:20, rep(1:10, 3), 
               rep(1:5, 5), rep(1:2, 10), rep(1, 20))
    ) %>%
    mutate(
        counts_cut_number   = cut_number(counts, n = 4),
        counts_cut_interval = cut_interval(counts, n = 4),
        counts_cut_width    = cut_width(counts, width = 25)
        ) 

# Data
skewed_tbl
#> # A tibble: 265 x 4
#>    counts counts_cut_number counts_cut_interval counts_cut_width
#>     <dbl> <fct>             <fct>               <fct>           
#>  1      1 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  2      2 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  3      3 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  4      4 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  5      5 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  6      6 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  7      7 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  8      8 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  9      9 (3,13]            [1,25.8]            [-12.5,12.5]    
#> 10     10 (3,13]            [1,25.8]            [-12.5,12.5]    
#> # ... with 255 more rows

summary(skewed_tbl$counts)
#>    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#>    1.00    3.00   13.00   25.75   42.00  100.00

# Histogram showing skew
skewed_tbl %>%
    ggplot(aes(counts)) +
    geom_histogram(bins = 30)

# cut_number() evenly distributes observations into bins by quantile
skewed_tbl %>%
    ggplot(aes(counts_cut_number)) +
    geom_bar()

# cut_interval() evenly splits the interval across the range
skewed_tbl %>%
    ggplot(aes(counts_cut_interval)) +
    geom_bar()

# cut_width() uses the width = 25 to create bins that are 25 in width
skewed_tbl %>%
    ggplot(aes(counts_cut_width)) +
    geom_bar()

Created on 2018-11-01 by the reprex package (v0.2.1)

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

Format telephone and credit card numbers in AngularJS

This is the simple way. As basic I took it from http://codepen.io/rpdasilva/pen/DpbFf, and done some changes. For now code is more simply. And you can get: in controller - "4124561232", in view "(412) 456-1232"

Filter:

myApp.filter 'tel', ->
  (tel) ->
    if !tel
      return ''
    value = tel.toString().trim().replace(/^\+/, '')

    city = undefined
    number = undefined
    res = null
    switch value.length
      when 1, 2, 3
        city = value
      else
        city = value.slice(0, 3)
        number = value.slice(3)
    if number
      if number.length > 3
        number = number.slice(0, 3) + '-' + number.slice(3, 7)
      else
        number = number
      res = ('(' + city + ') ' + number).trim()
    else
      res = '(' + city
    return res

And directive:

myApp.directive 'phoneInput', ($filter, $browser) ->

  require: 'ngModel'
  scope:
    phone: '=ngModel'
  link: ($scope, $element, $attrs) ->

    $scope.$watch "phone", (newVal, oldVal) ->
      value = newVal.toString().replace(/[^0-9]/g, '').slice 0, 10
      $scope.phone = value
      $element.val $filter('tel')(value, false)
      return
    return

Path of currently executing powershell script

From Get-ScriptDirectory to the Rescue blog entry ...

function Get-ScriptDirectory
{
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
}

Appropriate datatype for holding percent values?

If 2 decimal places is your level of precision, then a "smallint" would handle this in the smallest space (2-bytes). You store the percent multiplied by 100.

EDIT: The decimal type is probably a better match. Then you don't need to manually scale. It takes 5 bytes per value.

How to uninstall Apache with command line

Try this :

sc delete Apache2.4

or try this :

C:\Apache24\bin>httpd -k uninstall

hope this will be helpful

How do I force a favicon refresh?

When you request the favicon from Google, you can take a look at the response headers.

Last-Modified: Fri, 09 Jan 2009 16:35:02 GMT
Date: Thu, 01 Dec 2010 00:00:01 GMT
Expires: Fri, 01 Dec 2011 00:00:01 GMT
Cache-Control: public, max-age=31536000
Age: 7

If you put an "Expires: " header on the response, client browsers will re-request the icon after that timestamp. While doing active development, you could set the expires timestamp to a second or two in the future, and always have it fetch this, although that's a poor longterm plan.

ImportError: No module named xlsxwriter

I managed to resolve this issue as follows...

Be careful, make sure you understand the IDE you're using! - Because I didn't. I was trying to import xlsxwriter using PyCharm and was returning this error.

Assuming you have already attempted the pip installation (sudo pip install xlsxwriter) via your cmd prompt, try using another IDE e.g. Geany - & import xlsxwriter.

I tried this and Geany was importing the library fine. I opened PyCharm and navigated to 'File>Settings>Project:>Project Interpreter' xlslwriter was listed though intriguingly I couldn't import it! I double clicked xlsxwriter and hit 'install Package'... And thats it! It worked!

Hope this helps...

Custom HTTP Authorization Header

The format defined in RFC2617 is credentials = auth-scheme #auth-param. So, in agreeing with fumanchu, I think the corrected authorization scheme would look like

Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg="

Where FIRE-TOKEN is the scheme and the two key-value pairs are the auth parameters. Though I believe the quotes are optional (from Apendix B of p7-auth-19)...

auth-param = token BWS "=" BWS ( token / quoted-string )

I believe this fits the latest standards, is already in use (see below), and provides a key-value format for simple extension (if you need additional parameters).

Some examples of this auth-param syntax can be seen here...

http://tools.ietf.org/html/draft-ietf-httpbis-p7-auth-19#section-4.4

https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin

https://developers.google.com/accounts/docs/AuthSub#WorkingAuthSub

CSS background-image not working

In addition to display:block OR display:inline-block

Try giving sufficient padding to your .btn-pToolName and make sure you have the correct values for background-position

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

I was facing a similar issue. Actually the command is :

java -version and not java --version.

You will get output something like this:

java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

Match line break with regular expression

You could search for:

<li><a href="#">[^\n]+

And replace with:

$0</a>

Where $0 is the whole match. The exact semantics will depend on the language are you using though.


WARNING: You should avoid parsing HTML with regex. Here's why.

How to trigger the window resize event in JavaScript?

You can do this with this library. https://github.com/itmor/events-js

const events = new Events();

events.add({  
  blockIsHidden: () =>  {
    if ($('div').css('display') === 'none') return true;
  }
});

function printText () {
  console.log('The block has become hidden!');
}

events.on('blockIsHidden', printText);

Specify system property to Maven project

properties-maven-plugin plugin may help:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <goals>
                <goal>set-system-properties</goal>
            </goals>
            <configuration>
                <properties>
                    <property>
                        <name>my.property.name</name>
                        <value>my.property.value</value>
                    </property>
                </properties>
            </configuration>
        </execution>
    </executions>
</plugin>

UL has margin on the left

I don't see any margin or margin-left declarations for #footer-wrap li.

This ought to do the trick:

#footer-wrap ul,
#footer-wrap li {
    margin-left: 0;
    list-style-type: none;
}

How to disable an Android button?

With Kotlin you can do,

// to disable clicks
myButton.isClickable = false 

// to disable button
myButton.isEnabled = false

// to enable clicks
myButton.isClickable = true 

// to enable button
myButton.isEnabled = true

What is meaning of negative dbm in signal strength?

At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.

Thats why it always -ve.

Passing a dictionary to a function as keyword parameters

Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

So my example becomes:

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)

make arrayList.toArray() return more specific types

A shorter version of converting List to Array of specific type (for example Long):

Long[] myArray = myList.toArray(Long[]::new);

How to remove unwanted space between rows and columns in table?

Adding to vectran's answer: You also have to set cellspacing attribute on the table element for cross-browser compatibility.

<table cellspacing="0">

EDIT (for the sake of completeness I'm expanding this 5 years later:):

Internet Explorer 6 and Internet Explorer 7 required you to set cellspacing directly as a table attribute, otherwise the spacing wouldn't vanish.

Internet Explorer 8 and later versions and all other versions of popular browsers - Chrome, Firefox, Opera 4+ - support the CSS property border-spacing.

So in order to make a cross-browser table cell spacing reset (supporting IE6 as a dinosaur browser), you can follow the below code sample:

_x000D_
_x000D_
table{_x000D_
  border: 1px solid black;_x000D_
}_x000D_
table td {_x000D_
  border: 1px solid black; /* Style just to show the table cell boundaries */_x000D_
}_x000D_
_x000D_
_x000D_
table.no-spacing {_x000D_
  border-spacing:0; /* Removes the cell spacing via CSS */_x000D_
  border-collapse: collapse;  /* Optional - if you don't want to have double border where cells touch */_x000D_
}
_x000D_
<p>Default table:</p>_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<p>Removed spacing:</p>_x000D_
_x000D_
<table class="no-spacing" cellspacing="0"> <!-- cellspacing 0 to support IE6 and IE7 -->_x000D_
  <tr>_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do you run a SQL Server query from PowerShell?

There isn't a built-in "PowerShell" way of running a SQL query. If you have the SQL Server tools installed, you'll get an Invoke-SqlCmd cmdlet.

Because PowerShell is built on .NET, you can use the ADO.NET API to run your queries.

Two arrays in foreach loop

Your code like this is incorrect as foreach only for single array:

<?php
        $codes = array('tn','us','fr');
        $names = array('Tunisia','United States','France');

        foreach( $codes as $code and $names as $name ) {
            echo '<option value="' . $code . '">' . $name . '</option>';
            }
?>

Alternative, Change to this:

<?php
        $codes = array('tn','us','fr');
        $names = array('Tunisia','United States','France');
        $count = 0;

        foreach($codes as $code) {
             echo '<option value="' . $code . '">' . $names[count] . '</option>';
             $count++;
        }

?>

accessing a variable from another class

Filename=url.java

public class url {

    public static final String BASEURL = "http://192.168.1.122/";

}

if u want to call the variable just use this:

url.BASEURL + "your code here";

What does collation mean?

Collation can be simply thought of as sort order.

In English (and it's strange cousin, American), collation may be a pretty simple matter consisting of ordering by the ASCII code.

Once you get into those strange European languages with all their accents and other features, collation changes. For example, though the different accented forms of a may exist at disparate code points, they may all need to be sorted as if they were the same letter.

What exactly does numpy.exp() do?

It calculates ex for each x in your list where e is Euler's number (approximately 2.718). In other words, np.exp(range(5)) is similar to [math.e**x for x in range(5)].

How to get data from database in javascript based on the value passed to the function

Try the following:

<script> 
 //Functions to open database and to create, insert data into tables

 getSelectedRow = function(val)
    {
        db.transaction(function(transaction) {
              transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);

        });
    };
    selectedRowValues = function(transaction,results)
    {
         for(var i = 0; i < results.rows.length; i++)
         {
             var row = results.rows.item(i);
             alert(row['number']);
             alert(row['name']);                 
         }
    };
</script>

You don't have access to javascript variable names in SQL, you must pass the values to the Database.

Making RGB color in Xcode

The values are determined by the bit of the image. 8 bit 0 to 255

16 bit...some ridiculous number..0 to 65,000 approx.

32 bit are 0 to 1

I use .004 with 32 bit images...this gives 1.02 as a result when multiplied by 255

What is the difference between PUT, POST and PATCH?

Quite logical the difference between PUT & PATCH w.r.t sending full & partial data for replacing/updating respectively. However, just couple of points as below

  1. Sometimes POST is considered as for updates w.r.t PUT for create
  2. Does HTTP mandates/checks for sending full vs partial data in PATCH? Otherwise, PATCH may be quite same as update as in PUT/POST

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

Php multiple delimiters in explode

Try about using:

$output = preg_split('/ (@|vs) /', $input);

Can functions be passed as parameters?

I hope the below example will provide more clarity.

package main

type EmployeeManager struct{
    category            string
    city                string
    calculateSalary     func() int64
}


func NewEmployeeManager() (*EmployeeManager,error){

    return &EmployeeManager{
        category : "MANAGEMENT",
        city : "NY",
        calculateSalary: func() int64 {
            var calculatedSalary int64
            // some formula
            return calculatedSalary
        },
    },nil
}

func (self *EmployeeManager) emWithSalaryCalculation(){
    self.calculateSalary = func() int64 {
        var calculatedSalary int64
        // some new formula
        return calculatedSalary
    }
}

func updateEmployeeInfo(em EmployeeManager){
    // Some code
}

func processEmployee(){
    updateEmployeeInfo(struct {
        category        string
        city            string
        calculateSalary func() int64
    }{category: "", city: "", calculateSalary: func() int64 {
        var calculatedSalary int64
        // some new formula
        return calculatedSalary
    }})
}

Using Git with Visual Studio

The simplest solution that actually works quite well is to add the TortoiseGit commands as external tools.

Solution to adding a Git (TortoiseGit) toolbar to Visual Studio

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

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

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

How do I link a JavaScript file to a HTML file?

this is demo code but it will help 

<!DOCTYPE html>
<html>
<head>
<title>APITABLE 3</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>


$(document).ready(function(){

$.ajax({
    type: "GET",
    url: "https://reqres.in/api/users/",

    data: '$format=json',

    dataType: 'json',
    success: function (data) {
 $.each(data.data,function(d,results){
     console.log(data);

 $("#apiData").append(
                        "<tr>"
                          +"<td>"+results.first_name+"</td>"
                          +"<td>"+results.last_name+"</td>"
                          +"<td>"+results.id+"</td>"
                          +"<td>"+results.email+"</td>"
  +"<td>"+results.bentrust+"</td>"
                        +"</tr>" )
                    })
 } 

});

});


</script>
</head>
<body>


    <table id="apiTable">

        <thead>
            <tr>
            <th>Id</th>
            <br>
            <th>Email</th>
            <br>
            <th>Firstname</th>
            <br>
            <th>Lastname</th>
        </tr>
        </thead>
        <tbody id="apiData"></tbody>    





</body>
</html> 

Laravel Unknown Column 'updated_at'

Setting timestamps to false means you are going to lose both created_at and updated_at whereas you could set both of the keys in your model.

Case 1:

You have created_at column but not update_at you could simply set updated_at to false in your model

class ABC extends Model {

const UPDATED_AT = null;

Case 2:

You have both created_at and updated_at columns but with different column names

You could simply do:

class ABC extends Model {

const CREATED_AT = 'name_of_created_at_column';
const UPDATED_AT = 'name_of_updated_at_column';

Finally ignoring timestamps completely:

class ABC extends Model {

public $timestamps = false;

Show a message box from a class in c#?

using System.Windows.Forms;
...
MessageBox.Show("Hello World!");

How to get Maven project version to the bash command line

Should be easier since this bug is fixed in maven-help-plugin 3.0.0: MPH-99 Evaluate has no output in quiet mode.

C# MessageBox dialog result

This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:

//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

// If the no button was pressed ... 
if (result == DialogResult.No)
{
    ...
}

Hope it helps

Volatile vs Static in Java

In simple terms,

  1. static : static variables are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory

  2. volatile: This keyword is applicable to both class and instance variables.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads

Have a look at this article by Javin Paul to understand volatile variables in a better way.

enter image description here

In absence of volatile keyword, the value of variable in each thread's stack may be different. By making the variable as volatile, all threads will get same value in their working memory and memory consistency errors have been avoided.

Here the term variable can be either static (class) variable or instance (object) variable.

Regarding your query :

Anyway a static variable value is also going to be one value for all threads, then why should we go for volatile?

If I need instance variable in my application, I can't use static variable. Even in case of static variable, consistency is not guaranteed due to Thread cache as shown in the diagram.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.

What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change => memory consistency errors are still possible with volatile variables. To avoid side effects, you have to use synchronized variables. But there is a better solution in java.

Using simple atomic variable access is more efficient than accessing these variables through synchronized code

Some of the classes in the java.util.concurrent package provide atomic methods that do not rely on synchronization.

Refer to this high level concurrency control article for more details.

Especially have a look at Atomic variables.

Related SE questions:

Volatile Vs Atomic

Volatile boolean vs AtomicBoolean

Difference between volatile and synchronized in Java

Do sessions really violate RESTfulness?

No, using sessions does not necessarily violate RESTfulness. If you adhere to the REST precepts and constraints, then using sessions - to maintain state - will simply be superfluous. After all, RESTfulness requires that the server not maintain state.

What's a standard way to do a no-op in python?

If you need a function that behaves as a nop, try

nop = lambda *a, **k: None
nop()

Sometimes I do stuff like this when I'm making dependencies optional:

try:
    import foo
    bar=foo.bar
    baz=foo.baz
except:
    bar=nop
    baz=nop

# Doesn't break when foo is missing:
bar()
baz()

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

The proper way is to use Hibernate Transformers:

public class StudentDTO {
private String studentName;
private String courseDescription;

public StudentDTO() { }  
...
} 

.

List resultWithAliasedBean = s.createSQLQuery(
"SELECT st.name as studentName, co.description as courseDescription " +
"FROM Enrolment e " +
"INNER JOIN Student st on e.studentId=st.studentId " +
"INNER JOIN Course co on e.courseCode=co.courseCode")
.setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
.list();

StudentDTO dto =(StudentDTO) resultWithAliasedBean.get(0);

Iterating througth Object[] is redundant and would have some performance penalty. Detailed information about transofrmers usage you will find here: Transformers for HQL and SQL

If you are looking for even more simple solution you can use out-of-the-box-map-transformer:

List iter = s.createQuery(
"select e.student.name as studentName," +
"       e.course.description as courseDescription" +
"from   Enrolment as e")
.setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP )
.iterate();

String name = (Map)(iter.next()).get("studentName");

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

How to get URL of current page in PHP

if you want just the parts of url after http://domain.com, try this:

<?php echo $_SERVER['REQUEST_URI']; ?>

if the current url was http://domain.com/some-slug/some-id, echo will return only '/some-slug/some-id'.

if you want the full url, try this:

<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>

Printing result of mysql query from variable

$sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);

you can change LIMIT 1 to LIMIT any number you want

This will show you the last INSERTED row first.

How to break out of jQuery each Loop

I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.

$('.groupName').each(function() {
    if($(this).text() == groupname){
        alert('This group already exists');
        breakOut = true;
        return false;
    }
});
if(breakOut) {
    breakOut = false;
    return false;
} 

What is the difference between Integer and int in Java?

Integer is an wrapper class/Object and int is primitive type. This difference plays huge role when you want to store int values in a collection, because they accept only objects as values (until jdk1.4). JDK5 onwards because of autoboxing it is whole different story.

Why I can't change directories using "cd"?

You can combine an alias and a script,

alias proj="cd \`/usr/bin/proj !*\`"

provided that the script echos the destination path. Note that those are backticks surrounding the script name. 

For example, your script could be

#!/bin/bash
echo /home/askgelal/projects/java/$1

The advantage with this technique is that the script could take any number of command line parameters and emit different destinations calculated by possibly complex logic.

Facebook Like-Button - hide count?

It is now officially supported by Facebook. Just select the 'Button' layout.

https://developers.facebook.com/docs/plugins/like-button/

Insert HTML with React Variable Statements (JSX)

dangerouslySetInnerHTML has many disadvantage because it set inside the tag.

I suggest you to use some react wrapper like i found one here on npm for this purpose. html-react-parser does the same job.

import Parser from 'html-react-parser';
var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';


render: function() {
    return (
        <div className="content">{Parser(thisIsMyCopy)}</div>
    );
}

Very Simple :)

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

If you get this error in CollectionView try to create CustomCell file and Custom xib also.

add this code in ViewDidLoad() at mainVC.

    let nib = UINib(nibName: "CustomnibName", bundle: nil)
    self.collectionView.register(nib, forCellWithReuseIdentifier: "cell")

How to uninstall Ruby from /usr/local?

Create a symlink at /usr/bin named 'ruby' and point it to the latest installed ruby.

You can use something like ln -s /usr/bin/ruby /to/the/installed/ruby/binary

Hope this helps.

Is an entity body allowed for an HTTP DELETE request?

Might be the below GitHUb url will help you, to get the answer. Actually, Application Server like Tomcat, Weblogic denying the HTTP.DELETE call with request payload. So keeping these all things in mind, I have added example in github,please have a look into that

https://github.com/ashish720/spring-examples

How to stop flask application without using ctrl-c

You can use method bellow

app.do_teardown_appcontext()

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

The name 'model' does not exist in current context in MVC3

It took me ages to solve this issue, but finally I hope I have solved it on MVC, that is similar:

I have reinstall ASP.NET 4.5 (http://www.asp.net/downloads)

I have followed the upgrading tutorial on http://www.asp.net/whitepapers/mvc4-release-notes

BUT this mentioned paragraph is wrong for me

System.Web.Mvc, Version=4.0.0.0
System.Web.WebPages, Version=2.0.0.0
System.Web.Helpers, Version=2.0.0.0
System.Web.WebPages.Razor, Version=2.0.0.0

Because I have Razor in System.Web.Razor, so I changed the razor namespace to System.Web.Razor.

Add this to your web.config

<appSettings>
  <add key="webpages:Version" value="2.0.0.0" />
</appSettings>

I have add the assembly reference to all these assemblies above

Locate the ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.

That is all.

jQuery: Wait/Delay 1 second without executing code

function sleep(num) {
    var now = new Date();
    var stop = now.getTime() + num;
    while(true) {
        now = new Date();
        if(now.getTime() > stop) return;
    }
}

sleep(1000);   // 1 second 
alert('here');

this code work well for me.

How can I connect to MySQL on a WAMP server?

Just Change the Connection mysql string to 127.0.0.1 and it will work

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

json_decode() expects parameter 1 to be string, array given

  • Make an object

    $obj = json_decode(json_encode($need_to_json));

  • Show data from this $obj

    $obj->{'needed'};

Reference

How to get the first 2 letters of a string in Python?

Heres what the simple function would look like:

def firstTwo(string):
    return string[:2]

Understanding The Modulus Operator %

A novel way to find out the remainder is given below

Statement : Remainder is always constant

ex : 26 divided by 7 gives R : 5 

This can be found out easily by finding the number that completely divides 26 which is closer to the divisor and taking the difference of the both

13 is the next number after 7 that completely divides 26 because after 7 comes 8, 9, 10, 11, 12 where none of them divides 26 completely and give remainder 0.

So 13 is the closest number to 7 which divides to give remainder 0.

Now take the difference (13 ~ 7) = 5 which is the temainder.

Note: for this to work divisor should be reduced to its simplest form ex: if 14 is the divisor, 7 has to be chosen to find the closest number dividing the dividend.

How do you change the size of figures drawn with matplotlib?

Use this:

plt.figure(figsize=(width,height))

The width and height are in inches.
If not provided, defaults to rcParams["figure.figsize"] = [6.4, 4.8]. See more here.

Winforms issue - Error creating window handle

Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns... Then run your app and take a look at those columns for that app and see if one of those is growing really large.

It might be that you've got UI components that you think are cleaned up but haven't been Disposed.

Here's a link about this that might be helpful.

Good Luck!

How do I install Python 3 on an AWS EC2 instance?

Here is the one command to install python3 on Amazon linux ec2 instance:

$sudo yum install python3 -y

$python3 --version

Python 3.7.6

Import a file from a subdirectory?

Take a look at the Packages documentation (Section 6.4) here: http://docs.python.org/tutorial/modules.html

In short, you need to put a blank file named

__init__.py

in the "lib" directory.

Remove all elements contained in another array

If you're using Typescript and want to match on a single property value, this should work based on Craciun Ciprian's answer above.

You could also make this more generic by allowing non-object matching and / or multi-property value matching.

/**
 *
 * @param arr1 The initial array
 * @param arr2 The array to remove
 * @param propertyName the key of the object to match on
 */
function differenceByPropVal<T>(arr1: T[], arr2: T[], propertyName: string): T[] {
  return arr1.filter(
    (a: T): boolean =>
      !arr2.find((b: T): boolean => b[propertyName] === a[propertyName])
  );
}

'App not Installed' Error on Android

You should save this as Debug and not release, check the two JAR signs and also allow installing apps from where you have downloaded this (WhatsApp, chrome, etc...)

How to check if all elements of a list matches a condition?

You could use itertools's takewhile like this, it will stop once a condition is met that fails your statement. The opposite method would be dropwhile

for x in itertools.takewhile(lambda x: x[2] == 0, list)
    print x

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>

</body>
</html>

// authentication servlet class

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
            super();
        }
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

        }

        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while (rs.next()) {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");
                }

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    response.setContentType("text/html");
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");
                }
              }

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

How to swap String characters in Java?

StringBuilder sb = new StringBuilder("abcde");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
String newString = sb.toString();

Upload failed You need to use a different version code for your APK because you already have one with version code 2

This seems because you have already uploaded APK file of version 3 to Google Play Store. And again you are uploading apk with same version. So this issue has been occurred.

So for solution you need to change your version name and version code (increment with 1)and run application once and after export it upload to Google Play.

Arrays.asList() of an array

Use java.utils.Arrays:

public int getTheNumber(int[] factors) {
    int[] f = (int[])factors.clone();
    Arrays.sort(f);
    return f[0]*f[(f.length-1];
}

Or if you want to be efficient avoid all the object allocation just actually do the work:

public static int getTheNumber(int[] array) {
    if (array.length == 0)
        throw new IllegalArgumentException();
    int min = array[0];
    int max = array[0];
    for (int i = 1; i< array.length;++i) {
        int v = array[i];
        if (v < min) {
            min = v;
        } else if (v > max) {
            max = v;
        }
    }
    return min * max;
}

Iterating over a numpy array

see nditer

import numpy as np
Y = np.array([3,4,5,6])
for y in np.nditer(Y, op_flags=['readwrite']):
    y += 3

Y == np.array([6, 7, 8, 9])

y = 3 would not work, use y *= 0 and y += 3 instead.

How to add an Android Studio project to GitHub

First of all, create a Github account and project in Github. Go to the root folder and follow steps.

The most important thing we forgot here is ignoring the file. Every time we run Gradle or build it creates new files that are changeable from build to build and pc to pc. We do not want all the files from Android Studio to be added to Git. Files like generated code, binary files (executables) should not be added to Git (version control). So please use .gitignore file while uploading projects to Github. It also reduces the size of the project uploaded to the server.

  1. Go to root folder.
  2. git init
  3. Create .gitignore txt file in root folder. Place these content in the file. (this step not required if the file is auto-generated)

    *.iml .gradle /local.properties /.idea/workspace.xml /.idea/libraries .idea .DS_Store /build /captures .externalNativeBuild

  4. git add .
  5. git remote add origin https://github.com/username/project.git
  6. git commit - m "My First Commit"
  7. git push -u origin master

Note : As per suggestion from different developers, they always suggest to use git from the command line. It is up to you.

What is the difference between a cer, pvk, and pfx file?

Here are my personal, super-condensed notes, as far as this subject pertains to me currently, for anyone who's interested:

  • Both PKCS12 and PEM can store entire cert chains: public keys, private keys, and root (CA) certs.
  • .pfx == .p12 == "PKCS12"
    • fully encrypted
  • .pem == .cer == .cert == "PEM" (or maybe not... could be binary... see comments...)
    • base-64 (string) encoded X509 cert (binary) with a header and footer
      • base-64 is basically just a string of "A-Za-z0-9+/" used to represent 0-63, 6 bits of binary at a time, in sequence, sometimes with 1 or 2 "=" characters at the very end when there are leftovers ("=" being "filler/junk/ignore/throw away" characters)
      • the header and footer is something like "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" or "-----BEGIN ENCRYPTED PRIVATE KEY-----" and "-----END ENCRYPTED PRIVATE KEY-----"
    • Windows recognizes .cer and .cert as cert files
  • .jks == "Java Key Store"
    • just a Java-specific file format which the API uses
      • .p12 and .pfx files can also be used with the JKS API
  • "Trust Stores" contain public, trusted, root (CA) certs, whereas "Identity/Key Stores" contain private, identity certs; file-wise, however, they are the same.

Android open pdf file

The reason you don't have permissions to open file is because you didn't grant other apps to open or view the file on your intent. To grant other apps to open the downloaded file, include the flag(as shown below): FLAG_GRANT_READ_URI_PERMISSION

Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(getUriFromFile(localFile), "application/pdf");
browserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|
Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(browserIntent);

And for function:

getUriFromFile(localFile)

private Uri getUriFromFile(File file){
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        return Uri.fromFile(file);
    }else {
        return FileProvider.getUriForFile(itemView.getContext(), itemView.getContext().getApplicationContext().getPackageName() + ".provider", file);
    }
}

JAXB: How to ignore namespace during unmarshalling XML document?

In my situation, I have many namespaces and after some debug I find another solution just changing the NamespaceFitler class. For my situation (just unmarshall) this work fine.

 import javax.xml.namespace.QName;
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.SAXException;
 import org.xml.sax.helpers.XMLFilterImpl;
 import com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector;

 public class NamespaceFilter extends XMLFilterImpl {
    private SAXConnector saxConnector;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        if(saxConnector != null) {
            Collection<QName> expected = saxConnector.getContext().getCurrentExpectedElements();
            for(QName expectedQname : expected) {
                if(localName.equals(expectedQname.getLocalPart())) {
                    super.startElement(expectedQname.getNamespaceURI(), localName, qName, atts);
                    return;
                }
            }
        }
        super.startElement(uri, localName, qName, atts);
    }

    @Override
    public void setContentHandler(ContentHandler handler) {
        super.setContentHandler(handler);
        if(handler instanceof SAXConnector) {
            saxConnector = (SAXConnector) handler;
        }
    }
}

Ignore <br> with CSS?

As per your question, to solve this problem for Firefox and Opera using Aneesh Karthik C approach you need to add "float" right" attribute.

Check the example here. This CSS works in Firefox (26.0) , Opera (12.15), Chrome (32.0.1700) and Safari (7.0)

br {
   content: " ";  
   float:right; 
}

I hope this will answer your question!!

Correct way to quit a Qt program?

if you need to close your application from main() you can use this code

int main(int argc, char *argv[]){
QApplication app(argc, argv);
...
if(!QSslSocket::supportsSsl()) return app.exit(0);
...
return app.exec();
}

The program will terminated if OpenSSL is not installed

What is the symbol for whitespace in C?

No special escape sequence is required: you can just type the space directly:

if (char_i_want_to_test == ' ') { 
    // Do something because it is space
}

In ASCII, space is code 32, so you could specify space by '\x20' or even 32, but you really shouldn't do that.

Aside: the word "whitespace" is a catch all for space, tab, newline, and all of that. When you're referring specifically to the ordinary space character, you shouldn't use the term.

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

PHP Curl UTF-8 Charset

First method (internal function)

The best way I have tried before is to use urlencode(). Keep in mind, don't use it for the whole url; instead, use it only for the needed parts. For example, a request that has two 'text-fa' and 'text-en' fields and they contain a Persian and an English text, respectively, you might only need to encode the Persian text, not the English one.

Second Method (using cURL function)

However, there are better ways if the range of characters have to be encoded is more limited. One of these ways is using CURLOPT_ENCODING, by passing it to curl_setopt():

curl_setopt($ch, CURLOPT_ENCODING, "");

Center Contents of Bootstrap row container

For Bootstrap 4, use the below code:

<div class="mx-auto" style="width: 200px;">
  Centered element
</div>

Ref: https://getbootstrap.com/docs/4.0/utilities/spacing/#horizontal-centering

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

SQL: set existing column as Primary Key in MySQL

ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);

Check if a file exists or not in Windows PowerShell?

You want to use Test-Path:

Test-Path <path to file> -PathType Leaf

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

Check whether $_POST-value is empty

If the form was successfully submitted, $_POST['userName'] should always be set, though it may contain an empty string, which is different from not being set at all. Instead check if it is empty()

if (isset($_POST['submit'])) {
    if (empty($_POST['userName'])) {
        $username = 'Anonymous';
    } else { 
        $username = $_POST['userName'];
    }
}

Notice: Array to string conversion in

Store the Value of $_SESSION['username'] into a variable such as $username

$username=$_SESSION['username'];

$get = @mysql_query("SELECT money FROM players WHERE username = 
 '$username'");

it should work!

Why do we have to normalize the input for an artificial neural network?

It's explained well here.

If the input variables are combined linearly, as in an MLP [multilayer perceptron], then it is rarely strictly necessary to standardize the inputs, at least in theory. The reason is that any rescaling of an input vector can be effectively undone by changing the corresponding weights and biases, leaving you with the exact same outputs as you had before. However, there are a variety of practical reasons why standardizing the inputs can make training faster and reduce the chances of getting stuck in local optima. Also, weight decay and Bayesian estimation can be done more conveniently with standardized inputs.

How to import module when module name has a '-' dash or hyphen in it?

Starting from Python 3.1, you can use importlib :

import importlib  
foobar = importlib.import_module("foo-bar")

( https://docs.python.org/3/library/importlib.html )

JavaScript for detecting browser language preference

If you are developing a Chrome App / Extension use the chrome.i18n API.

chrome.i18n.getAcceptLanguages(function(languages) {
  console.log(languages);
  // ["en-AU", "en", "en-US"]
});

What's the difference between passing by reference vs. passing by value?

Here is an example:

#include <iostream>

void by_val(int arg) { arg += 2; }
void by_ref(int&arg) { arg += 2; }

int main()
{
    int x = 0;
    by_val(x); std::cout << x << std::endl;  // prints 0
    by_ref(x); std::cout << x << std::endl;  // prints 2

    int y = 0;
    by_ref(y); std::cout << y << std::endl;  // prints 2
    by_val(y); std::cout << y << std::endl;  // prints 2
}

What is the most effective way for float and double comparison?

You have to do this processing for floating point comparison, since float's can't be perfectly compared like integer types. Here are functions for the various comparison operators.

Floating Point Equal to (==)

I also prefer the subtraction technique rather than relying on fabs() or abs(), but I'd have to speed profile it on various architectures from 64-bit PC to ATMega328 microcontroller (Arduino) to really see if it makes much of a performance difference.

So, let's forget about all this absolute value stuff and just do some subtraction and comparison!

Modified from Microsoft's example here:

/// @brief      See if two floating point numbers are approximately equal.
/// @param[in]  a        number 1
/// @param[in]  b        number 2
/// @param[in]  epsilon  A small value such that if the difference between the two numbers is
///                      smaller than this they can safely be considered to be equal.
/// @return     true if the two numbers are approximately equal, and false otherwise
bool is_float_eq(float a, float b, float epsilon) {
    return ((a - b) < epsilon) && ((b - a) < epsilon);
}
bool is_double_eq(double a, double b, double epsilon) {
    return ((a - b) < epsilon) && ((b - a) < epsilon);
}

Example usage:

constexpr float EPSILON = 0.0001; // 1e-4
is_float_eq(1.0001, 0.99998, EPSILON);

I'm not entirely sure, but it seems to me some of the criticisms of the epsilon-based approach, as described in the comments below this highly-upvoted answer, can be resolved by using a variable epsilon, scaled according to the floating point values being compared, like this:

float a = 1.0001;
float b = 0.99998;
float epsilon = std::max(std::fabs(a), std::fabs(b)) * 1e-4;

is_float_eq(a, b, epsilon);

This way, the epsilon value scales with the floating point values and is therefore never so small of a value that it becomes insignificant.

For completeness, let's add the rest:

Greater than (>), and less than (<):

/// @brief      See if floating point number `a` is > `b`
/// @param[in]  a        number 1
/// @param[in]  b        number 2
/// @param[in]  epsilon  a small value such that if `a` is > `b` by this amount, `a` is considered
///             to be definitively > `b`
/// @return     true if `a` is definitively > `b`, and false otherwise
bool is_float_gt(float a, float b, float epsilon) {
    return a > b + epsilon;
}
bool is_double_gt(double a, double b, double epsilon) {
    return a > b + epsilon;
}

/// @brief      See if floating point number `a` is < `b`
/// @param[in]  a        number 1
/// @param[in]  b        number 2
/// @param[in]  epsilon  a small value such that if `a` is < `b` by this amount, `a` is considered
///             to be definitively < `b`
/// @return     true if `a` is definitively < `b`, and false otherwise
bool is_float_lt(float a, float b, float epsilon) {
    return a < b - epsilon;
}
bool is_double_lt(double a, double b, double epsilon) {
    return a < b - epsilon;
}

Greater than or equal to (>=), and less than or equal to (<=)

/// @brief      Returns true if `a` is definitively >= `b`, and false otherwise
bool is_float_ge(float a, float b, float epsilon) {
    return a > b - epsilon;
}
bool is_double_ge(double a, double b, double epsilon) {
    return a > b - epsilon;
}

/// @brief      Returns true if `a` is definitively <= `b`, and false otherwise
bool is_float_le(float a, float b, float epsilon) {
    return a < b + epsilon;
}
bool is_double_le(double a, double b, double epsilon) {
    return a < b + epsilon;
}

See also:

  1. The macro forms of some of the functions above in my repo here: utilities.h.
    1. UPDATE 29 NOV 2020: it's a work-in-progress, and I'm going to make it a separate answer when ready, but I've produced a better, scaled-epsilon version of all of the functions in C in this file here: utilities.c. Take a look.
  2. Additional reading I need to do now have done: Floating-point tolerances revisited, by Christer Ericson

How do I set the path to a DLL file in Visual Studio?

Another possibility would be to set the Working Directory under the debugging options to be the directory that has that DLL.

Edit: I was going to mention using a batch file to start Visual Studio (and set the PATH variable in the batch file). So then did a bit of searching and see that this exact same question was asked not long ago in this post. The answer suggests the batch file option as well as project settings that apparently may do the job (I did not test it).

How to determine the version of android SDK installed in computer?

You can check following path for Windows 10

C:\Users{user-name}\AppData\Local\Android\sdk\platforms

Also, you can check from android studio

File > Project Structure > SDK Location > Android SDK Location

How to set time zone of a java.util.Date?

You could also set the timezone at the JVM level

Date date1 = new Date();
System.out.println(date1);

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// or pass in a command line arg: -Duser.timezone="UTC"

Date date2 = new Date();
System.out.println(date2);

output:

Thu Sep 05 10:11:12 EDT 2013
Thu Sep 05 14:11:12 UTC 2013

Using HTML and Local Images Within UIWebView

Swift Version of Lithu T.V's answer:

webView.loadHTMLString(htmlString, baseURL: NSBundle.mainBundle().bundleURL)

How to create an object property from a variable value in JavaScript?

Dot notation and the properties are equivalent. So you would accomplish like so:

var myObj = new Object;
var a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1)

(alerts "whatever")

How can I split a text into sentences?

Using spacy:

import spacy

nlp = spacy.load('en_core_web_sm')
text = "How are you today? I hope you have a great day"
tokens = nlp(text)
for sent in tokens.sents:
    print(sent.string.strip())

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

Abuse leading to a one-expression solution for Matthew's answer:

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = (lambda f=x.copy(): (f.update(y), f)[1])()
>>> z
{'a': 1, 'c': 11, 'b': 10}

You said you wanted one expression, so I abused lambda to bind a name, and tuples to override lambda's one-expression limit. Feel free to cringe.

You could also do this of course if you don't care about copying it:

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = (x.update(y), x)[1]
>>> z
{'a': 1, 'b': 10, 'c': 11}

How to reference a local XML Schema file correctly?

If you work in MS Visual Studio just do following

  1. Put WSDL file and XSD file at the same folder.
  2. Correct WSDL file like this YourSchemeFile.xsd

  3. Use visual Studio using this great example How to generate service reference with only physical wsdl file

Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.

How to count items in JSON object using command line?

The shortest expression is

curl 'http://…' | jq length

Convert objective-c typedef to its string equivalent

Many answers all fairly good.

If you are after a generic, Objective C solution that uses some macros...

Key feature is it uses the enum as an index into a static array of NSString constants. the array itself is wrapped into a function to make it more like the suite of NSStringFromXXX functions prevalent in the Apple APIs.

you will need to #import "NSStringFromEnum.h" found here http://pastebin.com/u83RR3Vk

[EDIT] also needs #import "SW+Variadic.h" found here http://pastebin.com/UEqTzYLf

Example 1 : completely define a NEW enum typedef, with string converters.

in myfile.h


 #import "NSStringFromEnum.h"

 #define define_Dispatch_chain_cmd(enum)\
 enum(chain_done,=0)\
 enum(chain_entry)\
 enum(chain_bg)\
 enum(chain_mt)\
 enum(chain_alt)\
 enum(chain_for_c)\
 enum(chain_while)\
 enum(chain_continue_for)\
 enum(chain_continue_while)\
 enum(chain_break_for)\
 enum(chain_break_while)\
 enum(chain_previous)\
 enum(chain_if)\
 enum(chain_else)\


interface_NSString_Enum_DefinitionAndConverters(Dispatch_chain_cmd)

in myfile.m:


 #import "myfile.h"

 implementation_NSString_Enum_Converters(Dispatch_chain_cmd)

to use :

NSString *NSStringFromEnumDispatch_chain_cmd(enum Dispatch_chain_cmd value);

NSStringFromEnumDispatch_chain_cmd(chain_for_c) returns @"chain_for_c"

  enum Dispatch_chain_cmd enumDispatch_chain_cmdFromNSString(NSString *value);

enumDispatch_chain_cmdFromNSString(@"chain_previous") returns chain_previous

Example 2: provide conversion routines for an existing enum also demonstrates using a settings string, and renaming the typename used in the functions.

in myfile.h


 #import "NSStringFromEnum.h"


 #define CAEdgeAntialiasingMask_SETTINGS_PARAMS CAEdgeAntialiasingMask,mask,EdgeMask,edgeMask

 interface_NSString_Enum_Converters(CAEdgeAntialiasingMask_SETTINGS_PARAMS)

in myfile.m:


 // we can put this in the .m file as we are not defining a typedef, just the strings.
 #define define_CAEdgeAntialiasingMask(enum)\
 enum(kCALayerLeftEdge)\
 enum(kCALayerRightEdge)\
 enum(kCALayerBottomEdge)\
 enum(kCALayerTopEdge)



 implementation_NSString_Enum_Converters(CAEdgeAntialiasingMask_SETTINGS_PARAMS)

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

hibernate: LazyInitializationException: could not initialize proxy

See my article. I had the same problem - LazyInitializationException - and here's the answer I finally came up with:
http://community.jboss.org/wiki/LazyInitializationExceptionovercome
Setting lazy=false is not the answer - it can load everything all at once, and that's not necessarily good. Example:
1 record table A references:
5 records table B references:
25 records table C references:
125 records table D
...
etc. This is but one example of what can go wrong.
--Tim Sabin

How to select lines between two marker patterns which may occur multiple times with awk/sed

perl -lne 'print if((/abc/../mno/) && !(/abc/||/mno/))' your_file

Get most recent file in a directory on Linux

ls -Frt | grep "[^/]$" | tail -n 1

Created Button Click Event c#

if your button is inside your form class:

buttonOk.Click += new EventHandler(your_click_method);

(might not be exactly EventHandler)

and in your click method:

this.Close();

If you need to show a message box:

MessageBox.Show("test");

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

Here is the BESTEST way to send emails using PHPmailer library, this is the only method that works for me.

require_once 'mailer/class.phpmailer.php';
    $mail = new PHPMailer(); // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true; // authentication enabled
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 465; // or 587
    $mail->IsHTML(true);
    $mail->Username = "[email protected]";
    $mail->Password = "xxxxxxx";
    $mail->SetFrom("[email protected]");
    $mail->AddAddress($to);
    $logfile = dirname(dirname(__FILE__)) . '/mail.log';
    try {
        $mail->Body = $message;
        $mail->Subject = $subject;


        file_put_contents($logfile, "Content: \n", FILE_APPEND);
        file_put_contents($logfile, $message . "\n\n", FILE_APPEND);

        if(!$mail->Send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
            echo "Email has been sent";
        }
    } catch (Exception $e) {
        #print_r($e->getMessage());
        file_put_contents($logfile, "Error: \n", FILE_APPEND);
        file_put_contents($logfile, $e->getMessage() . "\n", FILE_APPEND);
        file_put_contents($logfile, $e->getTraceAsString() . "\n\n", FILE_APPEND);
    }

git: undo all working dir changes including new files

If you want to discard all changes, you can use any of the valid options in an alias in .gitconfig. For instance:

[alias]
    discard = "!f() { git add . && git stash && git stash drop stash@{0}; }; f"

Usage: git discard

Return JSON with error status code MVC

You have to return JSON error object yourself after setting the StatusCode, like so ...

if (BadRequest)
{
    Dictionary<string, object> error = new Dictionary<string, object>();
    error.Add("ErrorCode", -1);
    error.Add("ErrorMessage", "Something really bad happened");
    return Json(error);
}

Another way is to have a JsonErrorModel and populate it

public class JsonErrorModel
{
    public int ErrorCode { get; set;}

    public string ErrorMessage { get; set; }
}

public ActionResult SomeMethod()
{

    if (BadRequest)
    {
        var error = new JsonErrorModel
        {
            ErrorCode = -1,
            ErrorMessage = "Something really bad happened"
        };

        return Json(error);
    }

   //Return valid response
}

Take a look at the answer here as well

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

In Intellij version 2016, 2017, enable Preferences -> Compiler -> Annotation Processors does not work for me!

The following additional checkbox helps: enter image description here

How do you rename a MongoDB database?

There is no mechanism to re-name databases. The currently accepted answer at time of writing is factually correct and offers some interesting background detail as to the excuse upstream, but offers no suggestions for replicating the behavior. Other answers point at copyDatabase, which is no longer an option as the functionality has been removed in 4.0. I've updated SERVER-701 with my notes and incredulity.

Equivalent behavior involves mongodump and mongorestore in a bit of a dance:

  1. Export your data, making note of the "namespaces" in use. For example, on one of my datasets, I have a collection with the namespace byzmcbehoomrfjcs9vlj.Analytics — that prefix (actually the database name) will be needed in the next step.

  2. Import your data, supplying --nsFrom and --nsTo arguments. (Documentation.) Continuing with my above hypothetical (and extremely unreadable) example, to restore to a more sensical name, I invoke:

mongorestore --archive=backup.agz --gzip --drop \
    --nsFrom 'byzmcbehoomrfjcs9vlj.*' --nsTo 'rita.*'

Some may also point at the --db argument to mongorestore, however this, too, is deprecated and triggers a warning against use on non-BSON folder backups with a completely erroneous suggestion to "use --nsInclude instead". The above namespace translation is equivalent to use of the --db option, and is the correct namespace manipulation setup to use as we are not attempting to filter what is being restored.

Python Requests throwing SSLError

As pointed out by others, this problem "is caused by an untrusted SSL certificate". My answer is based on the top-rated answer and this answer.

You can test the certificate using curl:

curl -vvI https://example.com

If an error returns, you have 3 options:

  1. For a quick fix, you could just not verify the certificate:
requests.get('https://example.com', verify=False)
  1. Pass the path to the CA_BUNDLE file or directory with certificates of trusted CAs:
requests.get('https://example.com', verify='/path/to/certfile')
  1. If you have access to, fix the web server certificate.

My problem was because I was using only my site's certificate, not the intermediate (a.k.a. chain) certificate.

If you are using Let's Encrypt, you should use the fullchain.pem file, not cert.pem.

ArrayList insertion and retrieval order

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

What do *args and **kwargs mean?

Another good use for *args and **kwargs: you can define generic "catch all" functions, which is great for decorators where you return such a wrapper instead of the original function.

An example with a trivial caching decorator:

import pickle, functools
def cache(f):
  _cache = {}
  def wrapper(*args, **kwargs):
    key = pickle.dumps((args, kwargs))
    if key not in _cache:
      _cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache
    return _cache[key] # read value from cache
  functools.update_wrapper(wrapper, f) # update wrapper's metadata
  return wrapper

import time
@cache
def foo(n):
  time.sleep(2)
  return n*2

foo(10) # first call with parameter 10, sleeps
foo(10) # returns immediately

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

How to remove index.php from URLs?

Hi I'm late to the party.. just wanted to point out that the instructions from http://davidtsadler.com/archives/2012/06/03/how-to-install-magento-on-ubuntu/ were really useful.

I had Ubuntu server installed with Apache, MySql and Php so I thought I could jump to the heading Creating the directory from which Magento will be served from and I reached the same problem as the OP, i.e. I had 'index.php' needed in all the URLs (or I would get 404 not found). I then went back to Installing and configuring the Apache HTTP server and after restarting apache it works perfectly.

For reference, I was missing:

sudo bash -c "cat >> /etc/apache2/conf.d/servername.conf <<EOF
ServerName localhost
EOF"

... and

sudo a2enmod rewrite
sudo service apache2 restart

Hope this helps

What is a segmentation fault?

A segmentation fault is caused by a request for a page that the process does not have listed in its descriptor table, or an invalid request for a page that it does have listed (e.g. a write request on a read-only page).

A dangling pointer is a pointer that may or may not point to a valid page, but does point to an "unexpected" segment of memory.

Returning a boolean value in a JavaScript function

You could simplify this a lot:

  • Check whether one is not empty
  • Check whether they are equal

This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:

function validatePassword()
{
   var password = document.getElementById("password");
   var confirm_password = document.getElementById("password_confirm");

   return password.value !== "" && password.value === confirm_password.value;
       //       not empty       and              equal
}

What is difference between Lightsail and EC2?

In lightsail a virtual machine, SSD-based storage, data transfer, DNS management, and a static IP are all offered as a package. Whereas in normal case you provision an EC2 instance and then setup the rest of these things.Also Bandwidth included in the price, no security groups to set up, no need to worry about EBS volumes sizing.

Javascript to stop HTML5 video playback on modal window close

When you close the video you just need to pause it.

$("#closeSimple").click(function() {
    $("div#simpleModal").removeClass("show");
    $("#videoContainer")[0].pause();
    return false;                   
});

<video id="videoContainer" width="320" height="240" src="Davis_5109iPadFig3.m4v" controls="controls"> </video>

Also, for reference, here's the Opera documentation for scripting video controls.

What is the non-jQuery equivalent of '$(document).ready()'?

There is a standards based replacement,DOMContentLoaded that is supported by over 90%+ of browsers, but not IE8 (So below code use by JQuery for browser support):

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

jQuery's native function is much more complicated than just window.onload, as depicted below.

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            jQuery.ready();
        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                jQuery.ready();
            }
        });

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && window == window.top ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch( error ) {
                setTimeout( arguments.callee, 0 );
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        })();
    }

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );
}

Show two digits after decimal point in c++

It is possible to print a 15 decimal number in C++ using the following:

#include <iomanip>
#include <iostream>

cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl;
cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl;
cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl;
cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl;
_getch();

return 0;

How to Display Multiple Google Maps per page with API V3

Here's another example if you have the long and lat, in my case using Umbraco Google Map Datatype package and outputting a list of divs with class "map" eg.

<div class="map" id="UK">52.21454000000001,0.14044490000003407,13</div>

my JavaScript using Google Maps API v3 based on Cultiv Razor examples

$('.map').each(function (index, Element) {
    var coords = $(Element).text().split(",");
    if (coords.length != 3) {
        $(this).display = "none";
        return;
    }
    var latlng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
    var myOptions = {
        zoom: parseFloat(coords[2]),
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: false,
        mapTypeControl: true,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        }
    };
    var map = new google.maps.Map(Element, myOptions);

    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });
});

What is WebKit and how is it related to CSS?

Webkit is an HTML rendering engine used by Chrome and Safari.

It supports a number of custom CSS properties that are prefixed by -webkit-.

Merge Two Lists in R

In general one could,

merge_list <- function(...) by(v<-unlist(c(...)),names(v),base::c)

Note that the by() solution returns an attributed list, so it will print differently, but will still be a list. But you can get rid of the attributes with attr(x,"_attribute.name_")<-NULL. You can probably also use aggregate().

Add a reference column migration in Rails 4

if you like another alternate approach with up and down method try this:

  def up
    change_table :uploads do |t|
      t.references :user, index: true
    end
  end

  def down
    change_table :uploads do |t|
      t.remove_references :user, index: true
    end
  end

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

python: create list of tuples from lists

You're after the zip function.

Taken directly from the question: How to merge lists into a list of tuples in Python?

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]

How to compare variables to undefined, if I don’t know whether they exist?

if (document.getElementById('theElement')) // do whatever after this

For undefined things that throw errors, test the property name of the parent object instead of just the variable name - so instead of:

if (blah) ...

do:

if (window.blah) ...

How can I get my webapp's base URL in ASP.NET MVC?

@{
    var baseurl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + Url.Content("~");
}
@baseurl

--output http://localhost:49626/TEST/

Using context in a fragment

Use fragments from Support Library -

android.support.v4.app.Fragment

and then override

void onAttach (Context context) {
  this.context = context;
}

This way you can be sure that context will always be a non-null value.

Simple way to calculate median with MySQL

A simple way to calculate Median in MySQL

set @ct := (select count(1) from station);
set @row := 0;

select avg(a.val) as median from 
(select * from  table order by val) a
where (select @row := @row + 1)
between @ct/2.0 and @ct/2.0 +1;

How to tell if string starts with a number with Python?

You could use regular expressions.

You can detect digits using:

if(re.search([0-9], yourstring[:1])):
#do something

The [0-9] par matches any digit, and yourstring[:1] matches the first character of your string

How can I select from list of values in SQL Server

I know this is a pretty old thread, but I was searching for something similar and came up with this.

Given that you had a comma-separated string, you could use string_split

select distinct value from string_split('1, 1, 1, 2, 5, 1, 6',',')

This should return

1
2
5
6

String split takes two parameters, the string input, and the separator character.

you can add an optional where statement using value as the column name

select distinct value from string_split('1, 1, 1, 2, 5, 1, 6',',')
where value > 1

produces

2
5
6

Looping over arrays, printing both index and value

users=("kamal" "jamal" "rahim" "karim" "sadia")
index=()
t=-1

for i in ${users[@]}; do
  t=$(( t + 1 ))
  if [ $t -eq 0 ]; then
    for j in ${!users[@]}; do
      index[$j]=$j
    done
  fi
  echo "${index[$t]} is $i"
done

JQuery window scrolling event?

Check if the user has scrolled past the header ad, then display the footer ad.

if($(your header ad).position().top < 0) { $(your footer ad).show() }

Am I correct at what you are looking for?

Why do we need virtual functions in C++?

The virtual keyword forces the compiler to pick the method implementation defined in the object's class rather than in the pointer's class.

Shape *shape = new Triangle(); 
cout << shape->getName();

In the above example, Shape::getName will be called by default, unless the getName() is defined as virtual in the Base class Shape. This forces the compiler to look for the getName() implementation in the Triangle class rather than in the Shape class.

The virtual table is the mechanism in which the compiler keeps track of the various virtual-method implementations of the subclasses. This is also called dynamic dispatch, and there is some overhead associated with it.

Finally, why is virtual even needed in C++, why not make it the default behavior like in Java?

  1. C++ is based on the principles of "Zero Overhead" and "Pay for what you use". So it doesn't try to perform dynamic dispatch for you, unless you need it.
  2. To provide more control to the interface. By making a function non-virtual, the interface/abstract class can control the behavior in all its implementations.