Programs & Examples On #Cil

Common Intermediate Language is the object-oriented assembly language used by the .NET Framework and Mono. .NET languages compile to CIL, which is assembled into an object code that has a bytecode-style format.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

Select all occurrences of selected word in VSCode

Select All Occurrences of Find Match editor.action.selectHighlights.

Ctrl+Shift+L

Cmd+Shift+L or Cmd+Ctrl+G on Mac

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

I've tried everything suggested here but didn't work for me. So in case I can help anyone with a similar issue, every single tutorial I've checked is not updated to work with version 4.

Here is what I've done to make it work

import React from 'react';
import App from './App';

import ReactDOM from 'react-dom';
import {
    HashRouter,
    Route
} from 'react-router-dom';


 ReactDOM.render((
        <HashRouter>
            <div>
                <Route path="/" render={()=><App items={temasArray}/>}/>
            </div>
        </HashRouter >
    ), document.getElementById('root'));

That's the only way I have managed to make it work without any errors or warnings.

In case you want to pass props to your component for me the easiest way is this one:

 <Route path="/" render={()=><App items={temasArray}/>}/>

Disable Input fields in reactive form

If you want to disable first(formcontrol) then you can use below statement.

this.form.first.disable();

How to make two plots side-by-side using Python?

Change your subplot settings to:

plt.subplot(1, 2, 1)

...

plt.subplot(1, 2, 2)

The parameters for subplot are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1 means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2 means "a 1-row, 2-column figure: go to the second subplot."

You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:

side by side plot

In order to minimize the overlap of subplots, you might want to kick in a:

plt.tight_layout()

before the show. Yielding:

neater side by side plot

Sending private messages to user

Make the code say if (msg.content === ('trigger') msg.author.send('text')}

try/catch blocks with async/await

A cleaner alternative would be the following:

Due to the fact that every async function is technically a promise

You can add catches to functions when calling them with await

async function a(){
    let error;

    // log the error on the parent
    await b().catch((err)=>console.log('b.failed'))

    // change an error variable
    await c().catch((err)=>{error=true; console.log(err)})

    // return whatever you want
    return error ? d() : null;
}
a().catch(()=>console.log('main program failed'))

No need for try catch, as all promises errors are handled, and you have no code errors, you can omit that in the parent!!

Lets say you are working with mongodb, if there is an error you might prefer to handle it in the function calling it than making wrappers, or using try catches.

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

Verify host key with pysftp

Cook book to use different ways of pysftp.CnOpts() and hostkeys options.

Source : https://pysftp.readthedocs.io/en/release_0.2.9/cookbook.html

Host Key checking is enabled by default. It will use ~/.ssh/known_hosts by default. If you wish to disable host key checking (NOT ADVISED) you will need to modify the default CnOpts and set the .hostkeys to None.

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
    # do stuff here

To use a completely different known_hosts file, you can override CnOpts looking for ~/.ssh/known_hosts by specifying the file when instantiating.

import pysftp
cnopts = pysftp.CnOpts(knownhosts='path/to/your/knownhostsfile')

with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
    # do stuff here

If you wish to use ~/.ssh/known_hosts but add additional known host keys you can merge with update additional known_host format files by using .load method.

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys.load('path/to/your/extra_knownhosts')
with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
    # do stuff here

Body of Http.DELETE request in Angular2

deleteInsurance(insuranceId: any) {
    const insuranceData = {
      id : insuranceId
    }
    var reqHeader = new HttpHeaders({
            "Content-Type": "application/json",
        });
        const httpOptions = {
            headers: reqHeader,
            body: insuranceData,
        };
    return this.http.delete<any>(this.url + "users/insurance", httpOptions);
    }

In Visual Studio Code How do I merge between two local branches?

You can do it without using plugins.

In the latest version of vscode that I'm using (1.17.0) you can simply open the branch that you want (from the bottom left menu) then press ctrl+shift+p and type Git: Merge branch and then choose the other branch that you want to merge from (to the current one)

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

It's pretty simple. You're trying to test the wrapper component generated by calling connect()(MyPlainComponent). That wrapper component expects to have access to a Redux store. Normally that store is available as context.store, because at the top of your component hierarchy you'd have a <Provider store={myStore} />. However, you're rendering your connected component by itself, with no store, so it's throwing an error.

You've got a few options:

  • Create a store and render a <Provider> around your connected component
  • Create a store and directly pass it in as <MyConnectedComponent store={store} /> , as the connected component will also accept "store" as a prop
  • Don't bother testing the connected component. Export the "plain", unconnected version, and test that instead. If you test your plain component and your mapStateToProps function, you can safely assume the connected version will work correctly.

You probably want to read through the "Testing" page in the Redux docs: https://redux.js.org/recipes/writing-tests.

edit:

After actually seeing that you posted source, and re-reading the error message, the real problem is not with the SportsTopPane component. The problem is that you're trying to "fully" render SportsTopPane, which also renders all of its children, rather than doing a "shallow" render like you were in the first case. The line searchComponent = <SportsDatabase sportsWholeFramework="desktop" />; is rendering a component that I assume is also connected, and therefore expects a store to be available in React's "context" feature.

At this point, you have two new options:

  • Only do "shallow" rendering of SportsTopPane, so that you're not forcing it to fully render its children
  • If you do want to do "deep" rendering of SportsTopPane, you'll need to provide a Redux store in context. I highly suggest you take a look at the Enzyme testing library, which lets you do exactly that. See http://airbnb.io/enzyme/docs/api/ReactWrapper/setContext.html for an example.

Overall, I would note that you might be trying to do too much in this one component and might want to consider breaking it into smaller pieces with less logic per component.

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

You can use the template syntax of ngFor on groups and the usual syntax inside it for the actual rows like:

<table>
  <template let-group ngFor [ngForOf]="groups">
    <tr *ngFor="let row of group.items">{{row}}</tr>
  </template>
</table>

Check this plunk

Forward X11 failed: Network error: Connection refused

fill in the "X display location" did not work for me. but install MobaXterm did the job.

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

Applying an ellipsis to multiline text

This man have the best solution. Only css:

.multiline-ellipsis {
    display: block;
    display: -webkit-box;
    max-width: 400px;
    height: 109.2px;
    margin: 0 auto;
    font-size: 26px;
    line-height: 1.4;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

AWS EFS vs EBS vs S3 (differences & when to use?)

EBS is simple - block level storage which can be attached to an instance from same AZ, and can survive irrespective of instance life.

However, interesting difference is between EFS and S3, and to identify proper use cases for it.

Cost: EFS is approximately 10 times costly than S3.

Usecases:

  • Whenever we have thousands of instances who needs to process file simultaneously EFS is recommended over S3.
  • Also note that S3 is object based storage while EFS is file based it implies that whenever we have requirement that files are updated continuously (refreshed) we should use EFS.
  • S3 is eventually consistent while EFS is strong consistent. In case you can't afford eventual consistency, you should use EFS

How to export JSON from MongoDB using Robomongo

I don't think robomongo have such a feature. So you better use mongodb function as mongoexport for a specific Collection.

http://docs.mongodb.org/manual/reference/program/mongoexport/#export-in-json-format

But if you are looking for a backup solution is better to use

mongodump / mongorestore

How to customize Bootstrap 3 tab color

_x000D_
_x000D_
.panel.with-nav-tabs .panel-heading {_x000D_
  padding: 5px 5px 0 5px;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-tabs {_x000D_
  border-bottom: none;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-justified {_x000D_
  margin-bottom: -1px;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DEFAULT ***/_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
  background-color: #ddd;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:focus {_x000D_
  color: #555;_x000D_
  background-color: #fff;_x000D_
  border-color: #ddd;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f5f5f5;_x000D_
  border-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #555;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL PRIMARY ***/_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3071a9;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:focus {_x000D_
  color: #428bca;_x000D_
  background-color: #fff;_x000D_
  border-color: #428bca;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #428bca;_x000D_
  border-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  background-color: #4a9fe9;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL SUCCESS ***/_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #d6e9c6;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #fff;_x000D_
  border-color: #d6e9c6;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #dff0d8;_x000D_
  border-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3c763d;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL INFO ***/_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #bce8f1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #fff;_x000D_
  border-color: #bce8f1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #d9edf7;_x000D_
  border-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #31708f;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL WARNING ***/_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #faebcc;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #fff;_x000D_
  border-color: #faebcc;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #fcf8e3;_x000D_
  border-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #8a6d3b;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DANGER ***/_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #ebccd1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #fff;_x000D_
  border-color: #ebccd1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f2dede;_x000D_
  /* bg color */_x000D_
  border-color: #ebccd1;_x000D_
  /* border color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #a94442;_x000D_
  /* normal text color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ebccd1;_x000D_
  /* hover bg color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  /* active text color */_x000D_
  background-color: #a94442;_x000D_
  /* active bg color */_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">_x000D_
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<!------ Include the above in your HEAD tag ---------->_x000D_
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1>Panels with nav tabs.<span class="pull-right label label-default">:)</span></h1>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-default">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1default" data-toggle="tab">Default 1</a></li>_x000D_
            <li><a href="#tab2default" data-toggle="tab">Default 2</a></li>_x000D_
            <li><a href="#tab3default" data-toggle="tab">Default 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4default" data-toggle="tab">Default 4</a></li>_x000D_
                <li><a href="#tab5default" data-toggle="tab">Default 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1default">Default 1</div>_x000D_
            <div class="tab-pane fade" id="tab2default">Default 2</div>_x000D_
            <div class="tab-pane fade" id="tab3default">Default 3</div>_x000D_
            <div class="tab-pane fade" id="tab4default">Default 4</div>_x000D_
            <div class="tab-pane fade" id="tab5default">Default 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-primary">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1primary" data-toggle="tab">Primary 1</a></li>_x000D_
            <li><a href="#tab2primary" data-toggle="tab">Primary 2</a></li>_x000D_
            <li><a href="#tab3primary" data-toggle="tab">Primary 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4primary" data-toggle="tab">Primary 4</a></li>_x000D_
                <li><a href="#tab5primary" data-toggle="tab">Primary 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1primary">Primary 1</div>_x000D_
            <div class="tab-pane fade" id="tab2primary">Primary 2</div>_x000D_
            <div class="tab-pane fade" id="tab3primary">Primary 3</div>_x000D_
            <div class="tab-pane fade" id="tab4primary">Primary 4</div>_x000D_
            <div class="tab-pane fade" id="tab5primary">Primary 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-success">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1success" data-toggle="tab">Success 1</a></li>_x000D_
            <li><a href="#tab2success" data-toggle="tab">Success 2</a></li>_x000D_
            <li><a href="#tab3success" data-toggle="tab">Success 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4success" data-toggle="tab">Success 4</a></li>_x000D_
                <li><a href="#tab5success" data-toggle="tab">Success 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1success">Success 1</div>_x000D_
            <div class="tab-pane fade" id="tab2success">Success 2</div>_x000D_
            <div class="tab-pane fade" id="tab3success">Success 3</div>_x000D_
            <div class="tab-pane fade" id="tab4success">Success 4</div>_x000D_
            <div class="tab-pane fade" id="tab5success">Success 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-info">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1info" data-toggle="tab">Info 1</a></li>_x000D_
            <li><a href="#tab2info" data-toggle="tab">Info 2</a></li>_x000D_
            <li><a href="#tab3info" data-toggle="tab">Info 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4info" data-toggle="tab">Info 4</a></li>_x000D_
                <li><a href="#tab5info" data-toggle="tab">Info 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1info">Info 1</div>_x000D_
            <div class="tab-pane fade" id="tab2info">Info 2</div>_x000D_
            <div class="tab-pane fade" id="tab3info">Info 3</div>_x000D_
            <div class="tab-pane fade" id="tab4info">Info 4</div>_x000D_
            <div class="tab-pane fade" id="tab5info">Info 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-warning">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1warning" data-toggle="tab">Warning 1</a></li>_x000D_
            <li><a href="#tab2warning" data-toggle="tab">Warning 2</a></li>_x000D_
            <li><a href="#tab3warning" data-toggle="tab">Warning 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4warning" data-toggle="tab">Warning 4</a></li>_x000D_
                <li><a href="#tab5warning" data-toggle="tab">Warning 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1warning">Warning 1</div>_x000D_
            <div class="tab-pane fade" id="tab2warning">Warning 2</div>_x000D_
            <div class="tab-pane fade" id="tab3warning">Warning 3</div>_x000D_
            <div class="tab-pane fade" id="tab4warning">Warning 4</div>_x000D_
            <div class="tab-pane fade" id="tab5warning">Warning 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-danger">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1danger" data-toggle="tab">Danger 1</a></li>_x000D_
            <li><a href="#tab2danger" data-toggle="tab">Danger 2</a></li>_x000D_
            <li><a href="#tab3danger" data-toggle="tab">Danger 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4danger" data-toggle="tab">Danger 4</a></li>_x000D_
                <li><a href="#tab5danger" data-toggle="tab">Danger 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1danger">Danger 1</div>_x000D_
            <div class="tab-pane fade" id="tab2danger">Danger 2</div>_x000D_
            <div class="tab-pane fade" id="tab3danger">Danger 3</div>_x000D_
            <div class="tab-pane fade" id="tab4danger">Danger 4</div>_x000D_
            <div class="tab-pane fade" id="tab5danger">Danger 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<br/>
_x000D_
_x000D_
_x000D_

IndexError: too many indices for array

I think the problem is given in the error message, although it is not very easy to spot:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None).

This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function.

I highly recommend in your for loop inserting:

print(data)

This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.

sweet-alert display HTML code in text

All you have to do is enable the html variable to true.. I had same issue, all i had to do was html : true ,

    var hh = "<b>test</b>"; 
swal({
        title: "" + txt + "", 
        text: "Testno  sporocilo za objekt " + hh + "",  
        html: true,  
        confirmButtonText: "V redu", 
        allowOutsideClick: "true"  
});

Note: html : "Testno sporocilo za objekt " + hh + "",
may not work as html porperty is only use to active this feature by assign true / false value in the Sweetalert.
this html : "Testno sporocilo za objekt " + hh + "", is used in SweetAlert2

Make div 100% Width of Browser Window

There are new units that you can use:

vw - viewport width

vh - viewport height

#neo_main_container1
{
   width: 100%; //fallback
   width: 100vw;
}

Help / MDN

Opera Mini does not support this, but you can use it in all other modern browsers.

CanIUse

enter image description here

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Make sure that registry HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\ODP.NET\4.112.# DIIPath key is pointing to 32 bit Oarcle client BIN directory. For example, DIIPath value can be C:\app\User_name\11.2.0\client_32bit\bin

How to use XPath preceding-sibling correctly

You don't need to go level up and use .. since all buttons are on the same level:

//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

How to get an IFrame to be responsive in iOS Safari?

I needed a cross-browser solution. Requirements were:

  • needed to work on both iOS and elsewhere
  • don't have access to the content in the iFrame
  • need it to scroll!

Building off what I learned from @Idra regarding scrolling="no" on iOS and this post about fitting iFrame content to the screen in iOS here's what I ended up with. Hope it helps someone =)

HTML

<div id="url-wrapper"></div>

CSS

html, body{
    height: 100%;
}

#url-wrapper{
    margin-top: 51px;
    height: 100%;
}

#url-wrapper iframe{
    height: 100%;
    width: 100%;
}

#url-wrapper.ios{
    overflow-y: auto;
    -webkit-overflow-scrolling:touch !important;
    height: 100%;
}

#url-wrapper.ios iframe{
    height: 100%;
    min-width: 100%;
    width: 100px;
    *width: 100%;
}

JS

function create_iframe(url){

    var wrapper = jQuery('#url-wrapper');

    if(navigator.userAgent.match(/(iPod|iPhone|iPad)/)){
        wrapper.addClass('ios');
        var scrolling = 'no';
    }else{
        var scrolling = 'yes';
    }

    jQuery('<iframe>', {
        src: url,
        id:  'url',
        frameborder: 0,
        scrolling: scrolling
    }).appendTo(wrapper);

}

Android custom dropdown/popup menu

I know this is an old question, but I've found another answer that worked better for me and it doesn't seem to appear in any of the answers.

Create a layout xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dip"
    android:paddingBottom="5dip"
    android:paddingStart="10dip"
    android:paddingEnd="10dip">

<ImageView
    android:id="@+id/shoe_select_icon"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_gravity="center_vertical"
    android:scaleType="fitXY" />

<TextView
    android:id="@+id/shoe_select_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="20sp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"/>

</LinearLayout>

Create a ListPopupWindow and a map with the content:

ListPopupWindow popupWindow;
List<HashMap<String, Object>> data = new ArrayList<>();
HashMap<String, Object> map = new HashMap<>();
    map.put(TITLE, getString(R.string.left));
    map.put(ICON, R.drawable.left);
    data.add(map);
    map = new HashMap<>();
    map.put(TITLE, getString(R.string.right));
    map.put(ICON, R.drawable.right);
    data.add(map);

Then on click, display the menu using this function:

private void showListMenu(final View anchor) {
    popupWindow = new ListPopupWindow(this);

    ListAdapter adapter = new SimpleAdapter(
            this,
            data,
            R.layout.shoe_select,
            new String[] {TITLE, ICON}, // These are just the keys that the data uses (constant strings)
            new int[] {R.id.shoe_select_text, R.id.shoe_select_icon}); // The view ids to map the data to

    popupWindow.setAnchorView(anchor);
    popupWindow.setAdapter(adapter);
    popupWindow.setWidth(400);
    popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position){
                case 0:
                    devicesAdapter.setSelectedLeftPosition(devicesList.getChildAdapterPosition(anchor));
                    break;
                case 1:
                    devicesAdapter.setSelectedRightPosition(devicesList.getChildAdapterPosition(anchor));
                    break;
                default:
                    break;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    devicesAdapter.notifyDataSetChanged();
                }
            });
            popupWindow.dismiss();
        }
    });
    popupWindow.show();
}

Disable password authentication for SSH

I followed these steps (for Mac).

In /etc/ssh/sshd_config change

#ChallengeResponseAuthentication yes
#PasswordAuthentication yes

to

ChallengeResponseAuthentication no
PasswordAuthentication no

Now generate the RSA key:

ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa

(For me an RSA key worked. A DSA key did not work.)

A private key will be generated in ~/.ssh/id_rsa along with ~/.ssh/id_rsa.pub (public key).

Now move to the .ssh folder: cd ~/.ssh

Enter rm -rf authorized_keys (sometimes multiple keys lead to an error).

Enter vi authorized_keys

Enter :wq to save this empty file

Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

Restart the SSH:

sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd

Reading serial data in realtime in Python

You can use inWaiting() to get the amount of bytes available at the input queue.

Then you can use read() to read the bytes, something like that:

While True:
    bytesToRead = ser.inWaiting()
    ser.read(bytesToRead)

Why not to use readline() at this case from Docs:

Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.

You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)

How to create a sticky footer that plays well with Bootstrap 3

What worked for me was adding the position relative to the html tag.

html {
  min-height:100%;
  position:relative;
}
body {
  margin-bottom:60px;
}
footer {
  position:absolute;
  bottom:0;
  height:60px;
}

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I got this error message from using an oracle database in a docker despite the fact i had publish port to host option "-p 1521:1521". I was using jdbc url that was using ip address 127.0.0.1, i changed it to the host machine real ip address and everything worked then.

Create a new file in git bash

This is a very simple to create file in git bash at first write touch then file name with extension

for example

touch filename.extension

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

for bootstrap 3, this is what i used

.carousel-fade .carousel-inner .item {
  opacity: 0;
  -webkit-transition-property: opacity;
  -moz-transition-property: opacity;
  -o-transition-property: opacity;
  transition-property: opacity;
}
.carousel-fade .carousel-inner .active {
  opacity: 1;
}
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  opacity: 0;
  z-index: 1;
}
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}
.carousel-fade .carousel-control {
  z-index: 2;
}

Position Absolute + Scrolling

You need to wrap the text in a div element and include the absolutely positioned element inside of it.

<div class="container">
    <div class="inner">
        <div class="full-height"></div>
        [Your text here]
    </div>
</div>

Css:

.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }

Setting the inner div's position to relative makes the absolutely position elements inside of it base their position and height on it rather than on the .container div, which has a fixed height. Without the inner, relatively positioned div, the .full-height div will always calculate its dimensions and position based on .container.

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  border: solid 1px red;_x000D_
  height: 256px;_x000D_
  width: 256px;_x000D_
  overflow: auto;_x000D_
  float: left;_x000D_
  margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  position: relative;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 128px;_x000D_
  bottom: 0;_x000D_
  height: 100%;_x000D_
  background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="full-height">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="inner">_x000D_
    <div class="full-height">_x000D_
    </div>_x000D_
_x000D_
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
    maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
    cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
    quidem._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/M5cTN/

How to convert a boolean array to an int array

The 1*y method works in Numpy too:

>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False,  True,  True], dtype=bool)
>>> 1*y                      # Method 1
array([0, 0, 1, 1])
>>> y.astype(int)            # Method 2
array([0, 0, 1, 1]) 

If you are asking for a way to convert Python lists from Boolean to int, you can use map to do it:

>>> testList = [False, False,  True,  True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]

Or using list comprehensions:

>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]

Bootstrap carousel resizing image

The reason why your image is resizing which is because it is fluid. You have two ways to do it:

  1. Either give a fixed dimension to your image using CSS like:

    .carousel-inner > .item > img {
      width:640px;
      height:360px;
    }
  2. A second way to can do this:

    .carousel {
      width:640px;
      height:360px;
    }

<Django object > is not JSON serializable

Another great way of solving it while using a model is by using the values() function.

def returnResponse(date):
    response = ScheduledDate.objects.filter(date__startswith=date).values()
    return Response(response)

Tkinter: How to use threads to preventing main event loop from "freezing"

I have used RxPY which has some nice threading functions to solve this in a fairly clean manner. No queues, and I have provided a function that runs on the main thread after completion of the background thread. Here is a working example:

import rx
from rx.scheduler import ThreadPoolScheduler
import time
import tkinter as tk

class UI:
   def __init__(self):
      self.root = tk.Tk()
      self.pool_scheduler = ThreadPoolScheduler(1) # thread pool with 1 worker thread
      self.button = tk.Button(text="Do Task", command=self.do_task).pack()

   def do_task(self):
      rx.empty().subscribe(
         on_completed=self.long_running_task, 
         scheduler=self.pool_scheduler
      )

   def long_running_task(self):
      # your long running task here... eg:
      time.sleep(3)
      # if you want a callback on the main thread:
      self.root.after(5, self.on_task_complete)

   def on_task_complete(self):
       pass # runs on main thread

if __name__ == "__main__":
    ui = UI()
    ui.root.mainloop()

Another way to use this construct which might be cleaner (depending on preference):

tk.Button(text="Do Task", command=self.button_clicked).pack()

...

def button_clicked(self):

   def do_task(_):
      time.sleep(3) # runs on background thread
             
   def on_task_done():
      pass # runs on main thread

   rx.just(1).subscribe(
      on_next=do_task, 
      on_completed=lambda: self.root.after(5, on_task_done), 
      scheduler=self.pool_scheduler
   )

Auto submit form on page load

Try this On window load submit your form.

window.onload = function(){
  document.forms['member_signup'].submit();
}

How to connect mySQL database using C++

Found here:

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
   AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
  /* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column fata by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  }
  delete res;
  delete stmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " »
     << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}

Bootstrap Carousel Full Screen

Simply Add 'carousel-item' class in place of item class.

PHP add elements to multidimensional array with array_push

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);

jQuery set checkbox checked

I know this asks for a Jquery solution, but I just thought I'd point out that it is very easy to toggle this in plain javascript.

var element = document.getElementById("estado_cat");
element.checked = 1;

It will work in all current and future versions.

How to Convert UTC Date To Local time Zone in MySql Select Query

SELECT CONVERT_TZ() will work for that.but its not working for me.

Why, what error do you get?

SELECT CONVERT_TZ(displaytime,'GMT','MET');

should work if your column type is timestamp, or date

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_convert-tz

Test how this works:

SELECT CONVERT_TZ(a_ad_display.displaytime,'+00:00','+04:00');

Check your timezone-table

SELECT * FROM mysql.time_zone;
SELECT * FROM mysql.time_zone_name;

http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

If those tables are empty, you have not initialized your timezone tables. According to link above you can use mysql_tzinfo_to_sql program to load the Time Zone Tables. Please try this

shell> mysql_tzinfo_to_sql /usr/share/zoneinfo

or if not working read more: http://dev.mysql.com/doc/refman/5.5/en/mysql-tzinfo-to-sql.html

How to pass multiple values to single parameter in stored procedure

Either use a User Defined Table

Or you can use CSV by defining your own CSV function as per This Post.

I'd probably recommend the second method, as your stored proc is already written in the correct format and you'll find it handy later on if you need to do this down the road.

Cheers!

How to make android listview scrollable?

Listview so have inbuild scrolling capabilities. So you can not use listview inside scrollview. Encapsulate it in any other layout like LinearLayout or RelativeLayout.

Optimal way to concatenate/aggregate strings

For those of us who found this and are not using Azure SQL Database:

STRING_AGG() in PostgreSQL, SQL Server 2017 and Azure SQL
https://www.postgresql.org/docs/current/static/functions-aggregate.html
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

GROUP_CONCAT() in MySQL
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

(Thanks to @Brianjorden and @milanio for Azure update)

Example Code:

select Id
, STRING_AGG(Name, ', ') Names 
from Demo
group by Id

SQL Fiddle: http://sqlfiddle.com/#!18/89251/1

Can functions be passed as parameters?

You can also pass the function of a struct, like:

    package main
    // define struct
    type Apple struct {}
    
    // return apple's color
    func (Apple) GetColor() string {
         return "Red" 
    }
    
    func main () {
        // instantiate
        myApple := Apple{}
        
        // put the func in a variable
        theFunc := myApple.GetColor
        
        // execute the variable as a function
        color := theFunc()
    
        print(color)
    }

output will be "Red", check on the playground

What is System, out, println in System.out.println() in Java

The first answer you posted (System is a built-in class...) is pretty spot on.

You can add that the System class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out printstream to the native output stream associated with the "standard out" (console).

libstdc++.so.6: cannot open shared object file: No such file or directory

For Red Hat :

sudo yum install libstdc++.i686
sudo yum install libstdc++-devel.i686

Regular expression for address field validation

Just to add to Serzas' answer(since don't have enough reps. to comment). alphabets and numbers can effectively be replaced by \w for words. Additionally apostrophe,comma,period and hyphen doesn't necessarily need a backslash. My requirement also involved front and back slashes so \/ and finally whitespaces with \s. The working regex for me ,as such was :

pattern: "[\w',-\\/.\s]"

rsync - mkstemp failed: Permission denied (13)

I have Centos 7 server with rsyncd on board: /etc/rsyncd.conf

[files]
path = /files

By default selinux blocks access for rsyncd to /files folder

# this sets needed context to my /files folder
sudo semanage fcontext -a -t rsync_data_t '/files(/.*)?'
sudo restorecon -Rv '/files'
# sets needed booleans
sudo setsebool -P rsync_client 1

Disabling selinux is an easy but not a good solution

libaio.so.1: cannot open shared object file

I had to do the following (in Kubuntu 16.04.3):

  1. Install the libraries: sudo apt-get install libaio1 libaio-dev
  2. Find where the library is installed: sudo find / -iname 'libaio.a' -type f --> resulted in /usr/lib/x86_64-linux-gnu/libaio.a
  3. Add result to environment variable: export LD_LIBRARY_PATH="/usr/lib/oracle/12.2/client64/lib:/usr/lib/x86_64-linux-gnu"

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

You'll either have to upgrade the .NET 2 project to .NET 4, or downgrade the .NET 4 project to .NET 3.5 (or earlier).

How do you upgrade the .net version? I am not sure where to and what to specify. Please help.

Edit: I found the answer myself. Select the project, right click and choose Property Pages. There you can select framework version. or select the project and click Shift+F4

How to form a correct MySQL connection string?

Here is an example:

MySqlConnection con = new MySqlConnection(
    "Server=ServerName;Database=DataBaseName;UID=username;Password=password");

MySqlCommand cmd = new MySqlCommand(
    " INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
    OSGconv.deciLon+"')", con);

con.Open();
cmd.ExecuteNonQuery();
con.Close();

How do I convert a org.w3c.dom.Document object to a String?

use some thing like

import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

//method to convert Document to String
public String getStringFromDocument(Document doc)
{
    try
    {
       DOMSource domSource = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(domSource, result);
       return writer.toString();
    }
    catch(TransformerException ex)
    {
       ex.printStackTrace();
       return null;
    }
} 

Scroll part of content in fixed position container

It seems to work if you use

div#scrollable {
    overflow-y: scroll;
    height: 100%;
}

and add padding-bottom: 60px to div.sidebar.

For example: http://jsfiddle.net/AKL35/6/

However, I am unsure why it must be 60px.

Also, you missed the f from overflow-y: scroll;

SVN "Already Locked Error"

I had the same problem, It was solved when I checked the below checkbox

Drawing in Java using Canvas

Suggestions:

  • Don't use Canvas as you shouldn't mix AWT with Swing components unnecessarily.
  • Instead use a JPanel or JComponent.
  • Don't get your Graphics object by calling getGraphics() on a component as the Graphics object obtained will be transient.
  • Draw in the JPanel's paintComponent() method.
  • All this is well explained in several tutorials that are easily found. Why not read them first before trying to guess at this stuff?

Key tutorial links:

Oracle - Insert New Row with Auto Incremental ID

the complete know how, i have included a example of the triggers and sequence

create table temasforo(
idtemasforo NUMBER(5) PRIMARY KEY,
autor       VARCHAR2(50) NOT NULL,
fecha       DATE DEFAULT (sysdate),
asunto      LONG  );

create sequence temasforo_seq
  start with 1
  increment by 1
  nomaxvalue;

create or replace
trigger temasforo_trigger
  before insert on temasforo
  referencing OLD as old NEW as new
  for each row
  begin
      :new.idtemasforo:=temasforo_seq.nextval;
    end;

reference: http://thenullpointerexceptionx.blogspot.mx/2013/06/llaves-primarias-auto-incrementales-en.html

Regex to match any character including new lines

Yeap, you just need to make . match newline :

$string =~ /(START)(.+?)(END)/s;

Having issues with a MySQL Join that needs to meet multiple conditions

If you join the facilities table twice you will get what you are after:

select u.* 
from room u 
  JOIN facilities_r fu1 on fu1.id_uc = u.id_uc and fu1.id_fu = '4'
  JOIN facilities_r fu2 on fu2.id_uc = u.id_uc and fu2.id_fu = '3' 
where 1 and vizibility='1' 
group by id_uc 
order by u_premium desc, id_uc desc

REST API Authentication

I think the best approach is to use OAuth2. Google it and you will find a lot of useful posts to help you set it up.

It will make easier to develop client applications for your API from a web app or a mobile one.

Hope it helps you.

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I had to modify some bits for this to work for me. I am using Bootstrap 3 and jQuery 2

// Javascript to enable link to tab
var hash = document.location.hash;
var prefix = "!";
if (hash) {
    hash = hash.replace(prefix,'');
    var hashPieces = hash.split('?');
    activeTab = $('[role="tablist"] a[href=' + hashPieces[0] + ']');
    activeTab && activeTab.tab('show');
}

// Change hash for page-reload
$('[role="tablist"] a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash.replace("#", "#" + prefix);
});

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

Importing a function from a class in another file?

You can use the below syntax -

from FolderName.FileName import Classname

using "if" and "else" Stored Procedures MySQL

I think that this construct: if exists (select... is specific for MS SQL. In MySQL EXISTS predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

You can rewrite the above lines of code like this:

DELIMITER $$

CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)

BEGIN
    DECLARE count_prim INT;
    DECLARE count_sec INT;

    SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
    SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;

    if (count_prim > 0) then
        set resultado = 0;
    elseif (count_sec > 0) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
    SELECT resultado;
END

How can I reconcile detached HEAD with master/origin?

As pointed by Chris, I had following situation

git symbolic-ref HEAD fails with fatal: ref HEAD is not a symbolic ref

However git rev-parse refs/heads/master was pointing to a good commit from where I could recover (In my case last commit and you can see that commit by using git show [SHA]

I did a lot messy things after that, but what seems to have fixed is just,

git symbolic-ref HEAD refs/heads/master

And head is re attached!

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

posting hidden value

Maybe a little late to the party but why don't you use sessions to store your data?

bookingfacilities.php

session_start();
$_SESSION['form_date'] = $date;

successfulbooking.php

session_start();
$date = $_SESSION['form_date']; 

Nobody will see this.

Strange Jackson exception being thrown when serializing Hibernate object

You could use @JsonIgnoreProperties(value = { "handler", "hibernateLazyInitializer" }) annotation on your class "Director"

SQL UPDATE with sub-query that references the same table in MySQL

Abstract example with clearer table and column names:

UPDATE tableName t1
INNER JOIN tableName t2 ON t2.ref_column = t1.ref_column
SET t1.column_to_update = t2.column_desired_value

As suggested by @Nico

Hope this help someone.

Method to Add new or update existing item in Dictionary

Could there be any problem if i replace Method-1 by Method-2?

No, just use map[key] = value. The two options are equivalent.


Regarding Dictionary<> vs. Hashtable: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false); and the add parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

There is possibly a quicker way, but I would do:

a <- rnorm(100) # Our data
q <- quantile(a) # You can supply your own breaks, see ?quantile

# Define a simple function that checks in which quantile a number falls
getQuant <- function(x)
   {
   for (i in 1:(length(q)-1))
       {
       if (x>=q[i] && x<q[i+1])
          break;
       }
   i
   }

# Apply the function to the data
res <- unlist(lapply(as.matrix(a), getQuant))

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

Plot a legend outside of the plotting area in base graphics?

I can offer only an example of the layout solution already pointed out.

layout(matrix(c(1,2), nrow = 1), widths = c(0.7, 0.3))
par(mar = c(5, 4, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
par(mar = c(5, 0, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, ylim=c(-2,2), type = "n", axes = FALSE, ann = FALSE)
legend(1, 1, c("group A", "group B"), pch = c(1,2), lty = c(1,2))

an ugly picture :S

How to Animate Addition or Removal of Android ListView Rows

Since Android is open source, you don't actually need to reimplement ListView's optimizations. You can grab ListView's code and try to find a way to hack in the animation, you can also open a feature request in android bug tracker (and if you decided to implement it, don't forget to contribute a patch).

FYI, the ListView source code is here.

Padding a table row

This is a very old post, but I thought I should post my solution of a similar problem I faced recently.

Answer : I solved this issue by displaying the tr element as a block element i.e. specifying a CSS of display:block for the tr element. You can see this in code sample below.

_x000D_
_x000D_
<style>_x000D_
  tr {_x000D_
    display: block;_x000D_
    padding-bottom: 20px;_x000D_
  }_x000D_
  table {_x000D_
    border: 1px solid red;_x000D_
  }_x000D_
</style>_x000D_
<table>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <h2>Lorem Ipsum</h2>_x000D_
        <p>Fusce sodales lorem nec magna iaculis a fermentum lacus facilisis. Curabitur sodales risus sit amet neque fringilla feugiat. Ut tellus nulla, bibendum at faucibus ut, convallis eget neque. In hac habitasse platea dictumst. Nullam elit enim, gravida_x000D_
          eu blandit ut, pellentesque nec turpis. Proin faucibus, sem sed tempor auctor, ipsum velit pellentesque lorem, ut semper lorem eros ac eros. Vivamus mi urna, tempus vitae mattis eget, pretium sit amet sapien. Curabitur viverra lacus non tortor_x000D_
          luctus vitae euismod purus hendrerit. Praesent ut venenatis eros. Nulla a ligula erat. Mauris lobortis tempus nulla non scelerisque._x000D_
        </p>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<br>_x000D_
<br>This TEXT IS BELOW and OUTSIDE the TABLE element. NOTICE how the red table border is pushed down below the end of paragraph due to bottom padding being specified for the tr element. The key point here is that the tr element must be displayed as a block_x000D_
in order for padding to apply at the tr level.
_x000D_
_x000D_
_x000D_

Scroll to a div using jquery

First get the position of the div element upto which u want to scroll by jQuery position() method.
Example : var pos = $("div").position();
Then get the y cordinates (height) of that element with ".top" method.
Example : pos.top;
Then get the x cordinates of the that div element with ".left" method.
These methods are originated from CSS positioning.
Once we get x & y cordinates, then we can use javascript's scrollTo(); method.
This method scrolls the document upto specific height & width.
It takes two parameters as x & y cordinates. Syntax : window.scrollTo(x,y);
Then just pass the x & y cordinates of the DIV element in the scrollTo() function.
Refer the example below ↓ ↓

<!DOCTYPE HTML>
    <html>
    <head>
        <title>
            Scroll upto Div with jQuery.
        </title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#button1").click(function () {
                    var x = $("#element").position(); //gets the position of the div element...
                    window.scrollTo(x.left, x.top); //window.scrollTo() scrolls the page upto certain position....
                    //it takes 2 parameters : (x axis cordinate, y axis cordinate);
                });
            });
            </script>
    </head>
    <body>
        <button id="button1">
            Click here to scroll
        </button>

        <div id="element" style="position:absolute;top:200%;left:0%;background-color:orange;height:100px;width:200px;">
            The DIV element.
            </div>
        </body>
    </html>

LINQ Contains Case Insensitive

IndexOf works best in this case

return this
   .ObjectContext
   .FACILITY_ITEM
   .Where(fi => fi.DESCRIPTION.IndexOf(description, StringComparison.OrdinalIgnoreCase)>=0);

jQuery table sort

@Nick Grealy's answer is great, but it does not take into account possible rowspan attributes of the table header cells (and probably the other answers don't do it either). Here is an improvement of the @Nick Grealy's answer which fixes that. Based on this answer too (thanks @Andrew Orlov).

I've also replaced the $.isNumeric function with a custom one (thanks @zad) to make it work with older jQuery versions.

To activate it, add class="sortable" to the <table> tag.

$(document).ready(function() {

    $('table.sortable th').click(function(){
        var table = $(this).parents('table').eq(0);
        var column_index = get_column_index(this);
        var rows = table.find('tbody tr').toArray().sort(comparer(column_index));
        this.asc = !this.asc;
        if (!this.asc){rows = rows.reverse()};
        for (var i = 0; i < rows.length; i++){table.append(rows[i])};
    })

});

function comparer(index) {
    return function(a, b) {
        var valA = getCellValue(a, index), valB = getCellValue(b, index);
        return isNumber(valA) && isNumber(valB) ? valA - valB : valA.localeCompare(valB);
    }
}
function getCellValue(row, index){ return $(row).children('td').eq(index).html() };

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function get_column_index(element) {
    var clickedEl = $(element);
    var myCol = clickedEl.closest("th").index();
    var myRow = clickedEl.closest("tr").index();
    var rowspans = $("th[rowspan]");
    rowspans.each(function () {
        var rs = $(this);
        var rsIndex = rs.closest("tr").index();
        var rsQuantity = parseInt(rs.attr("rowspan"));
        if (myRow > rsIndex && myRow <= rsIndex + rsQuantity - 1) {
            myCol++;
        }
    });
    // alert('Row: ' + myRow + ', Column: ' + myCol);
    return myCol;
};

CLEAR SCREEN - Oracle SQL Developer shortcut?

SQL>Clear Screen (It is used the Clear The Screen FUlly in SQL Plus Window)

Create SQLite database in android

A simple database example to insert Todo List of day today life in DB and get list of all todo list.

public class MyDatabaseHelper extends SQLiteOpenHelper {

// Logcat tag
private static final String LOG = "DatabaseHelper";

// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "SQLiteDemoDB";

// Table Names
private static final String TABLE_TODO = "todos";

// column names
private static final String KEY_ID = "id";
private static final String KEY_CREATED_AT = "created_at";
private static final String KEY_TODO = "todoDescr";

// *********************************************************************************************
public MyDatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_TABLE_TODO);


}

// Upgrading database **************************************************************************
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);


    // Create tables again
    onCreate(db);
}

// Creating Table TABLE_TEAM
String CREATE_TABLE_TODO = "CREATE TABLE " + TABLE_TODO + "("
        + KEY_ID + " integer primary key autoincrement, "
        + KEY_TODO + " text, "
        + KEY_CREATED_AT + " text" + ")";


// insert values of todo
public boolean InsertTodoDetails(String todo, String createdAt) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_TODO, todo);
    contentValues.put(KEY_CREATED_AT, createdAt);


    long rowInserted = db.insert(TABLE_TODO, null, contentValues);
    db.close();
    return true;
}


// Select values of todo
public Cursor GetAllTodoDetails() {
    SQLiteDatabase db = this.getReadableDatabase();


    String query = "SELECT * FROM " + TABLE_TODO;
    Cursor mcursor = db.rawQuery(query, null);

    if (mcursor != null) {
        mcursor.moveToFirst();
    }

    return mcursor;

}



}

My activity To save and get the record.

public class MyDbActivity extends AppCompatActivity {

    @Bind(R.id.edt_todo)
    EditText edtTodo;
    @Bind(R.id.btn_save)
    Button btnSave;

    MyDatabaseHelper db;
    @Bind(R.id.btn_getTodo)
    Button btnGetTodo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_db);
        ButterKnife.bind(this);

// creating database object
        db = new MyDatabaseHelper(this);


    }

    @OnClick(R.id.btn_save)
    public void onViewClicked() {


        String datetime = "";
        try {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            datetime = dateformat.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }

        db.InsertTodoDetails(edtTodo.getText().toString().trim(), datetime);

    }

    @OnClick(R.id.btn_getTodo)
    public void onGetTodoClicked() {
        String todos = "";
        Cursor TodoList = db.GetAllTodoDetails();
        if (TodoList.moveToFirst()) {
            do {
                if (todos.equals("")) {
                    todos = TodoList.getString(TodoList.getColumnIndex("todoDescr"));

                } else {
                    todos = todos + ", " + TodoList.getString(TodoList.getColumnIndex("todoDescr"));
                }
                // do what ever you want here
            } while (TodoList.moveToNext());
        }
        TodoList.close();
        Toast.makeText(this, "" + todos, Toast.LENGTH_SHORT).show();

    }
}

How do I vertically align text in a div?

I use the following to vertically center random elements easily:

HTML:

<div style="height: 200px">
    <div id="mytext">This is vertically aligned text within a div</div>
</div>

CSS:

#mytext {
    position: relative;
    top: 50%; 
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

This centers the text in my div to the exact vertical middle of a 200px-high outer div. Note that you may need to use a browser prefix (like -webkit- in my case) to make this work for your browser.

This works not only for text, but also for other elements.

Using CSS to insert text

It is, but requires a CSS2 capable browser (all major browsers, IE8+).

.OwnerJoe:before {
  content: "Joe's Task:";
}

But I would rather recommend using Javascript for this. With jQuery:

$('.OwnerJoe').each(function() {
  $(this).before($('<span>').text("Joe's Task: "));
});

Create a simple HTTP server with Java?

Use Jetty. Here's the official example for embedding Jetty. (Here's an outdated tutorial.)

Jetty is pretty lightweight, but it does provide a servlet container, which may contradict your requirement against using an "application server".

You can embed the Jetty server into your application. Jetty allows EITHER embedded OR servlet container options.

Here is one more quick get started tutorial along with the source code.

Something better than .NET Reflector?

JetBrains is going to add a decompiler to its ReSharper, and release a stand-alone decompiler too.

The good news is that we’re preparing a standalone binary-as-a-source application, i.e. a decompiler + assembly browser to explore whatever .NET compiled code is legal to explore. We don’t have any specific date for release, but it’s going to be released this year, and it’s going to be free of charge. And by saying “free”, we actually mean “free”.

Here is more information.

UPDATE: JetBrains has now released the product called dotPeek and it can be found here.

Open Source Alternatives to Reflector?

I am currently working on an open-source disassembler / decompiler called Assembly Analyzer. It generates source code for methods, displays assembly metadata and resources, and allows you to walk through dependencies.

The project is hosted on CodePlex => http://asmanalyzer.codeplex.com/

JSON string to JS object

the string in your question is not a valid json string. From json.org website:

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is 
  realized as an object, record, struct, dictionary, hash table, keyed list, or
  associative array.
* An ordered list of values. In most languages, this is realized as an
  array, vector, list, or sequence.

Basically a json string will always start with either { or [.

Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.

IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.

Do you (really) write exception safe code?

Writing exception-safe code in C++ is not so much about using lots of try { } catch { } blocks. It's about documenting what kind of guarantees your code provides.

I recommend reading Herb Sutter's Guru Of The Week series, in particular installments 59, 60 and 61.

To summarize, there are three levels of exception safety you can provide:

  • Basic: When your code throws an exception, your code does not leak resources, and objects remain destructible.
  • Strong: When your code throws an exception, it leaves the state of the application unchanged.
  • No throw: Your code never throws exceptions.

Personally, I discovered these articles quite late, so much of my C++ code is definitely not exception-safe.

SQL SELECT from multiple tables

SELECT 
  pid, 
  cid, 
  pname, 
  name1, 
  null 
FROM 
  product p
INNER JOIN 
  customer1 c ON p.cid = c.cid
UNION
SELECT 
  pid, 
  cid, 
  pname, 
  null, 
  name2
FROM 
  product p
INNER JOIN 
  customer2 c ON p.cid = c.cid

Does Android support near real time push notification?

If you can depend on the Google libraries being there for you target market, then you may want to piggy back on GTalk functionality (registering a resource on the existing username - the intercepting it the messages as they come in with a BroadcastReceiver).

If not, and I expect you can't, then you're into bundling your own versions of XMPP. This is a pain, but may be made easier if XMPP is bundled separately as a standalone library.

You may also consider PubSubHubub, but I have no idea the network usage of it. I believe it is built atop of XMPP.

Travel/Hotel API's?

HotelsCombined has an easy-to-access and useful service to download the data feed files with hotels. Not exactly API, but something you can get, parse and use. Here is how you do it:

  1. Go to http://www.hotelscombined.com/Affiliates.aspx
  2. Register there (no company or bank data is needed)
  3. Open “Data feeds” page
  4. Choose “Standard data feed” -> “Single file” -> “CSV format” (you may get XML as well)

If you are interested in details, you may find the sample Python code to filter CSV file to get hotels for a specific city here:

http://mikhail.io/2012/05/17/api-to-get-the-list-of-hotels/

Update:

Unfortunately, HotelsCombined.com has introduced the new regulations: they've restricted the access to data feeds by default. To get the access, a partner must submit some information on why one needs the data. The HC team will review it and then (maybe) will grant access.

cannot call member function without object

You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:

int main()
{
   Name_pairs np;
   cout << "Enter names and ages. Use 0 to cancel.\n";
   while(np.test())
   {
      np.read_names();
      np.read_ages();
   }
   np.print();
   keep_window_open();
}

jquery change div text

I think this will do:

$('#'+div_id+' .widget-head > span').text("new dialog title");

JavaScript global event mechanism

If you want unified way to handle both uncaught errors and unhandled promise rejections you may have a look on uncaught library.

EDIT

<script type="text/javascript" src=".../uncaught/lib/index.js"></script>

<script type="text/javascript">
    uncaught.start();
    uncaught.addListener(function (error) {
        console.log('Uncaught error or rejection: ', error.message);
    });
</script>

It listens window.unhandledrejection in addition to window.onerror.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I had the same problem when I tried to commit a deleted package (which contains various java classes but nothing from the package was necessary any more).

My solution / workaround in order to fix the problem:

  • I reverted the whole package
  • deleted the content first
  • commited the deleted content
  • finally I commited the deleted package again (and it worked in most cases :-))

However, from time to time it was not possible to commit a deleted package (which contains nothing)

My workaround:

  • I created a dummy class in the package
  • and after that I repeated the steps mentioned above

My last hint...

But sometimes it helps simple to synchronize the package / project once more and after that everything works great again.



About my configuration:

  • Eclipse Neon
  • SVN Interface: JavaHL (JNI) 1.8.13 (r1667537)
  • VisualSVN Server Manager, Version: 3.3.1



Maybe I could help someone with one of my hints.

How to set array length in c# dynamically

Use this:

 Array.Resize(ref myArr, myArr.Length + 5);

WPF chart controls

Another one is OxyPlot, which is an open-source cross-platform (WPF, Silverlight, WinForms, Mono) .Net plotting library.

How do I shrink my SQL Server Database?

You will also need to shrink the individual data files.

It is however not a good idea to shrink the databases. For example see here

Reading the selected value from asp:RadioButtonList using jQuery

According to me it'll be working fine...

Just try with this

   var GetValue=$('#radiobuttonListId').find(":checked").val();

The Radiobuttonlist value to be stored on GetValue(Variable).

How do I remove carriage returns with Ruby?

What do you get when you do puts lines? That will give you a clue.

By default File.open opens the file in text mode, so your \r\n characters will be automatically converted to \n. Maybe that's the reason lines are always equal to lines2. To prevent Ruby from parsing the line ends use the rb mode:

C:\> copy con lala.txt
a
file
with
many
lines
^Z

C:\> irb
irb(main):001:0> text = File.open('lala.txt').read
=> "a\nfile\nwith\nmany\nlines\n"
irb(main):002:0> bin = File.open('lala.txt', 'rb').read
=> "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n"
irb(main):003:0>

But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter File.read.

Efficiently replace all accented characters in a string?

Basing on existing answers and some suggestions, I've created this one:

String.prototype.removeAccents = function() {

    var removalMap = {
        'A'  : /[A?AÀÁÂ????ÃAA??????ÄA?Å?A??????A]/g,
        'AA' : /[?]/g,
        'AE' : /[Æ??]/g,
        'AO' : /[?]/g,
        'AU' : /[?]/g,
        'AV' : /[??]/g,
        'AY' : /[?]/g,
        'B'  : /[B?B??????]/g,
        'C'  : /[C?CCCCCÇ????]/g,
        'D'  : /[D?D?D????Ð??Ð?]/g,
        'DZ' : /[??]/g,
        'Dz' : /[??]/g,
        'E'  : /[E?EÈÉÊ?????E??EEË?E??????E????]/g,
        'F'  : /[F?F?ƒ?]/g,
        'G'  : /[G?G?G?GGGGG????]/g,
        'H'  : /[H?HH??????H???]/g,
        'I'  : /[I?IÌÍÎIIIIÏ??I???I?I]/g,
        'J'  : /[J?JJ?]/g,
        'K'  : /[K?K?K?K???????]/g,
        'L'  : /[L?L?LL??L??L??????]/g,
        'LJ' : /[?]/g,
        'Lj' : /[?]/g,
        'M'  : /[M?M?????]/g,
        'N'  : /[N?N?NÑ?N?N??????]/g,
        'NJ' : /[?]/g,
        'Nj' : /[?]/g,
        'O'  : /[O?OÒÓÔ????Õ???O??O??Ö??OO??O???????OOØ??O??]/g,
        'OI' : /[?]/g,
        'OO' : /[?]/g,
        'OU' : /[?]/g,
        'P'  : /[P?P???????]/g,
        'Q'  : /[Q?Q???]/g,
        'R'  : /[R?RR?R????R??????]/g,
        'S'  : /[S?S?S?S?Š????S???]/g,
        'T'  : /[T?T?T??T??T?T??]/g,
        'TZ' : /[?]/g,
        'U'  : /[U?UÙÚÛU?U?UÜUUUU?UUU??U???????U???]/g,
        'V'  : /[V?V?????]/g,
        'VY' : /[?]/g,
        'W'  : /[W?W??W????]/g,
        'X'  : /[X?X??]/g,
        'Y'  : /[Y?Y?ÝY???Ÿ?????]/g,
        'Z'  : /[Z?ZZ?ZŽ???????]/g,
        'a'  : /[a?a?àáâ????ãaa??????äa?å?a??????a??]/g,
        'aa' : /[?]/g,
        'ae' : /[æ??]/g,
        'ao' : /[?]/g,
        'au' : /[?]/g,
        'av' : /[??]/g,
        'ay' : /[?]/g,
        'b'  : /[b?b???b??]/g,
        'c'  : /[c?cccccç?????]/g,
        'd'  : /[d?d?d????d????]/g,
        'dz' : /[??]/g,
        'e'  : /[e?eèéê?????e??eeë?e??????e?????]/g,
        'f'  : /[f?f?ƒ?]/g,
        'g'  : /[g?g?g?ggggg????]/g,
        'h'  : /[h?hh???????h???]/g,
        'hv' : /[?]/g,
        'i'  : /[i?iìíîiiiï??i???i??i]/g,
        'j'  : /[j?jjj?]/g,
        'k'  : /[k?k?k?k???????]/g,
        'l'  : /[l?l?ll??l???ll?????]/g,
        'lj' : /[?]/g,
        'm'  : /[m?m?????]/g,
        'n'  : /[n?n?nñ?n?n???????]/g,
        'nj' : /[?]/g,
        'o'  : /[o?oòóô????õ???o??o??ö??oo??o???????ooø?????]/g,
        'oi' : /[?]/g,
        'ou' : /[?]/g,
        'oo' : /[?]/g,
        'p'  : /[p?p???????]/g,
        'q'  : /[q?q???]/g,
        'r'  : /[r?rr?r????r??????]/g,
        's'  : /[s?sßs?s?š????s????]/g,
        't'  : /[t?t??t??t??t????]/g,
        'tz' : /[?]/g,
        'u'  : /[u?uùúûu?u?uüuuuu?uuu??u???????u???]/g,
        'v'  : /[v?v?????]/g,
        'vy' : /[?]/g,
        'w'  : /[w?w??w?????]/g,
        'x'  : /[x?x??]/g,
        'y'  : /[y?y?ýy???ÿ??????]/g,
        'z'  : /[z?zz?zž??z????]/g,
    };

    var str = this;

    for(var latin in removalMap) {
      var nonLatin = removalMap[latin];
      str = str.replace(nonLatin , latin);
    }

    return str;
}

It uses real chars instead of unicode list and works well.

You can use it like

"aaa".removeAccents(); // returns "aaa"

You can easily convert this function to not be string prototype. However, as I'm fan of using string prototype in such cases, you'll have to do it yourself.

How can you flush a write using a file descriptor?

Have you tried disabling buffering?

setvbuf(fd, NULL, _IONBF, 0);

Scanning Java annotations at runtime

There's a wonderful comment by zapp that sinks in all those answers:

new Reflections("my.package").getTypesAnnotatedWith(MyAnnotation.class)

What is LDAP used for?

Well, there are LDAP servers and the LDAP protocol. Combined, it's a data store, or a database. It's not relational, but it's just a place to store data, and it's optimized to be efficient at reads more than writes. It doesn't support transactions.

Now, it happens to be very popular for storing credentials, but that's by no means its only purpose, and not its original purpose.

Position an element relative to its container

You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:

div.parent{
    position: relative;
    left: 0px;  /* stick it wherever it was positioned by default */
    top: 0px;
}

div.child{
    position: absolute;
    left: 10px;
    top: 10px;
}

How to document Python code using Doxygen

Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.

For generating API docs from Python docstrings, the leading tools are pdoc and pydoctor. Here's pydoctor's generated API docs for Twisted and Bazaar.

Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "pydoc" command line tool and as well as the help() function available in the interactive interpreter.

Dynamically load a JavaScript file

I used a much less complicated version recently with jQuery:

<script src="scripts/jquery.js"></script>
<script>
  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
  var $head = $("head");
  for (var i = 0; i < js.length; i++) {
    $head.append("<script src=\"" + js[i] + "\"></scr" + "ipt>");
  }
</script>

It worked great in every browser I tested it in: IE6/7, Firefox, Safari, Opera.

Update: jQuery-less version:

<script>
  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
  for (var i = 0, l = js.length; i < l; i++) {
    document.getElementsByTagName("head")[0].innerHTML += ("<script src=\"" + js[i] + "\"></scr" + "ipt>");
  }
</script>

Options for HTML scraping?

Well, if you want it done from the client side using only a browser you have jcrawl.com. After having designed your scrapping service from the web application (http://www.jcrawl.com/app.html), you only need to add the generated script to an HTML page to start using/presenting your data.

All the scrapping logic happens on the the browser via JavaScript. I hope you find it useful. Click this link for a live example that extracts the latest news from Yahoo tennis.

What do these operators mean (** , ^ , %, //)?

You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:

  • The ** operator does exponentiation. a ** b is a raised to the b power. The same ** symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).
  • The ^ operator does a binary xor. a ^ b will return a value with only the bits set in a or in b but not both. This one is simple!
  • The % operator is mostly to find the modulus of two integers. a % b returns the remainder after dividing a by b. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b, rather than the same sign as a. The same operator is also used for the "old" style of string formatting, so a % b can return a string if a is a format string and b is a value (or tuple of values) which can be inserted into a.
  • The // operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b). In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division at the top of your files. I strongly recommend it!)

Present and dismiss modal view controller

presentModalViewController:

MainViewController *mainViewController=[[MainViewController alloc]init];
[self.navigationController presentModalViewController:mainViewController animated:YES];

dismissModalViewController:

[self dismissModalViewControllerAnimated:YES];

PHP array printing using a loop

either foreach:

foreach($array as $key => $value) {
  // do something with $key and $value
}

or with for:

for($i = 0, $l = count($array); $i < $l; ++$i) {
  // do something with $array[$i]
}

obviously you can only access the keys when using a foreach loop.

if you want to print the array (keys and) values just for debugging use var_dump or print_r

Is there a command to undo git init?

In windows, type rmdir .git or rmdir /s .git if the .git folder has subfolders.

If your git shell isn't setup with proper administrative rights (i.e. it denies you when you try to rmdir), you can open a command prompt (possibly as administrator--hit the windows key, type 'cmd', right click 'command prompt' and select 'run as administrator) and try the same commands.

rd is an alternative form of the rmdir command. http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/rmdir.mspx?mfr=true

How to handle static content in Spring MVC?

The URLRewrite is sort of a "hack" if you want to call it that. What it comes down to is, you're re-inventing the wheel; as there are already existing solutions. Another thing to remember is Http Server = Static content & App server = dynamic content (this is how they were designed). By delegating the appropriate responsibilities to each server you maximize efficiency... but now-a-days this is probably only a concern in a performance critical environments and something like Tomcat would most likely work well in both roles most of the time; but it is still something to keep in mind none the less.

How to make cross domain request

If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather). I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.

How to create correct JSONArray in Java using JSONObject

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }

How to annotate MYSQL autoincrement field with JPA annotations

If you are using MariaDB this will work

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

For more, you can check https://thorben-janssen.com/hibernate-tips-use-auto-incremented-column-primary-key/

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

How can I get the error message for the mail() function?

$e=error_get_last();
if($e['message']!==''){
    // An error function
}

error_get_last(); - return the last error that occurred

String vs. StringBuilder

Further to the previous answers, the first thing I always do when thinking of issues like this is to create a small test application. Inside this app, perform some timing test for both scenarios and see for yourself which is quicker.

IMHO, appending 500+ string entries should definitely use StringBuilder.

Conditionally formatting cells if their value equals any value of another column

Another simpler solution is to use this formula in the conditional formatting (apply to column A):

=COUNTIF(B:B,A1)

Regards!

How can I convert a date to GMT?

I was just working on this, I may be a bit late, but I did a workaround. Here are steps: - Get current time from whatever timezone the app is fired.- - Get time zone offset of that zone from gmt 0. then add your timezone value in miliseconds. You will get the date in your time zone. I added some extra code to remove anything after the actual time.

getCurrentDate() {
    var date = new Date();
    var newDate = new Date(8 * 60 * 60000 + date.valueOf() + 
                           (date.getTimezoneOffset() * 60000));
    var ampm = newDate.getHours() < 12 ? ' AM' : ' PM';
    var strDate = newDate + '';
    return (strDate).substring(0, strDate.indexOf(' GMT')) + ampm
}

Running code after Spring Boot starts

Best way you use CommandLineRunner or ApplicationRunner The only difference between is run() method CommandLineRunner accepts array of string and ApplicationRunner accepts ApplicationArugument.

How to include external Python code to use in other files?

If you use:

import Math

then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.

If you want to import a module's functions without having to prefix them, you must explicitly name them, like:

from Math import Calculate, Add, Subtract

Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:

from Math import *

However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.

Style the first <td> column of a table differently

This should help. Its CSS3 :first-child where you should say that the first tr of the table you would like to style. http://reference.sitepoint.com/css/pseudoclass-firstchild

ORA-00918: column ambiguously defined in SELECT *

You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:

SELECT DISTINCT
    coaches.id,
    people.*,
    users.*,
    coaches.*
FROM "COACHES"
    INNER JOIN people ON people.id = coaches.person_id
    INNER JOIN users ON coaches.person_id = users.person_id
    LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
    rownum <= 25

It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.

Getting the absolute path of the executable, using C#?

The one that worked for me and isn't above was Process.GetCurrentProcess().MainModule.FileName.

How do I print a double value without scientific notation using Java?

You can try it with DecimalFormat. With this class you are very flexible in parsing your numbers.
You can exactly set the pattern you want to use.
In your case for example:

double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678

Find nearest value in numpy array

Here's an extension to find the nearest vector in an array of vectors.

import numpy as np

def find_nearest_vector(array, value):
  idx = np.array([np.linalg.norm(x+y) for (x,y) in array-value]).argmin()
  return array[idx]

A = np.random.random((10,2))*100
""" A = array([[ 34.19762933,  43.14534123],
   [ 48.79558706,  47.79243283],
   [ 38.42774411,  84.87155478],
   [ 63.64371943,  50.7722317 ],
   [ 73.56362857,  27.87895698],
   [ 96.67790593,  77.76150486],
   [ 68.86202147,  21.38735169],
   [  5.21796467,  59.17051276],
   [ 82.92389467,  99.90387851],
   [  6.76626539,  30.50661753]])"""
pt = [6, 30]  
print find_nearest_vector(A,pt)
# array([  6.76626539,  30.50661753])

Scroll to the top of the page using JavaScript?

The equivalent solution in TypeScript may be as the following

   window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });

How to find the operating system version using JavaScript?

I started to write a Script to read OS and browser version that can be tested on Fiddle. Feel free to use and extend.
Breaking Change:
Since September 2020 the new Edge gets detected. So 'Microsoft Edge' is the new version based on Chromium and the old Edge is now detected as 'Microsoft Legacy Edge'!

/**
 * JavaScript Client Detection
 * (C) viazenetti GmbH (Christian Ludwig)
 */
(function (window) {
    {
        var unknown = '-';

        // screen
        var screenSize = '';
        if (screen.width) {
            width = (screen.width) ? screen.width : '';
            height = (screen.height) ? screen.height : '';
            screenSize += '' + width + " x " + height;
        }

        // browser
        var nVer = navigator.appVersion;
        var nAgt = navigator.userAgent;
        var browser = navigator.appName;
        var version = '' + parseFloat(navigator.appVersion);
        var majorVersion = parseInt(navigator.appVersion, 10);
        var nameOffset, verOffset, ix;

        // Opera
        if ((verOffset = nAgt.indexOf('Opera')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 6);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // Opera Next
        if ((verOffset = nAgt.indexOf('OPR')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 4);
        }
        // Legacy Edge
        else if ((verOffset = nAgt.indexOf('Edge')) != -1) {
            browser = 'Microsoft Legacy Edge';
            version = nAgt.substring(verOffset + 5);
        } 
        // Edge (Chromium)
        else if ((verOffset = nAgt.indexOf('Edg')) != -1) {
            browser = 'Microsoft Edge';
            version = nAgt.substring(verOffset + 4);
        }
        // MSIE
        else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
        }
        // Chrome
        else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
            browser = 'Chrome';
            version = nAgt.substring(verOffset + 7);
        }
        // Safari
        else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
            browser = 'Safari';
            version = nAgt.substring(verOffset + 7);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // Firefox
        else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
            browser = 'Firefox';
            version = nAgt.substring(verOffset + 8);
        }
        // MSIE 11+
        else if (nAgt.indexOf('Trident/') != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(nAgt.indexOf('rv:') + 3);
        }
        // Other browsers
        else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
            browser = nAgt.substring(nameOffset, verOffset);
            version = nAgt.substring(verOffset + 1);
            if (browser.toLowerCase() == browser.toUpperCase()) {
                browser = navigator.appName;
            }
        }
        // trim the version string
        if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

        majorVersion = parseInt('' + version, 10);
        if (isNaN(majorVersion)) {
            version = '' + parseFloat(navigator.appVersion);
            majorVersion = parseInt(navigator.appVersion, 10);
        }

        // mobile version
        var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

        // cookie
        var cookieEnabled = (navigator.cookieEnabled) ? true : false;

        if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
            document.cookie = 'testcookie';
            cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
        }

        // system
        var os = unknown;
        var clientStrings = [
            {s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 3.11', r:/Win16/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Chrome OS', r:/CrOS/},
            {s:'Linux', r:/(Linux|X11(?!.*CrOS))/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];
        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(nAgt)) {
                os = cs.s;
                break;
            }
        }

        var osVersion = unknown;

        if (/Windows/.test(os)) {
            osVersion = /Windows (.*)/.exec(os)[1];
            os = 'Windows';
        }

        switch (os) {
            case 'Mac OS':
            case 'Mac OS X':
            case 'Android':
                osVersion = /(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                break;
        }
        
        // flash (you'll need to include swfobject)
        /* script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" */
        var flashVersion = 'no check';
        if (typeof swfobject != 'undefined') {
            var fv = swfobject.getFlashPlayerVersion();
            if (fv.major > 0) {
                flashVersion = fv.major + '.' + fv.minor + ' r' + fv.release;
            }
            else  {
                flashVersion = unknown;
            }
        }
    }

    window.jscd = {
        screen: screenSize,
        browser: browser,
        browserVersion: version,
        browserMajorVersion: majorVersion,
        mobile: mobile,
        os: os,
        osVersion: osVersion,
        cookies: cookieEnabled,
        flashVersion: flashVersion
    };
}(this));

alert(
    'OS: ' + jscd.os +' '+ jscd.osVersion + '\n' +
    'Browser: ' + jscd.browser +' '+ jscd.browserMajorVersion +
      ' (' + jscd.browserVersion + ')\n' + 
    'Mobile: ' + jscd.mobile + '\n' +
    'Flash: ' + jscd.flashVersion + '\n' +
    'Cookies: ' + jscd.cookies + '\n' +
    'Screen Size: ' + jscd.screen + '\n\n' +
    'Full User Agent: ' + navigator.userAgent
);

Can I override and overload static methods in Java?

As any static method is part of class not instance so it is not possible to override static method

How to set Internet options for Android emulator?

On a slightly different note, I had to make a virtual device without GSM Modem Support so that the internet on my emulator would work.

Move existing, uncommitted work to a new branch in Git

3 Steps to Commit your changes

Suppose you have created a new branch on GitHub with the name feature-branch.

enter image description here

FETCH

    git pull --all         Pull all remote branches
    git branch -a          List all branches now

Checkout and switch to the feature-branch directory. You can simply copy the branch name from the output of branch -a command above

git checkout -b feature-branch

VALIDATE

Next use the git branch command to see the current branch. It will show feature-branch with * In front of it

git branch         

COMMIT

git add .   add all files
git commit -m "Rafactore code or use your message"

Take update and the push changes on the origin server

 git pull origin feature-branch
 git push origin feature-branch

What is the perfect counterpart in Python for "while not EOF"

You can use below code snippet to read line by line, till end of file

line = obj.readline()
while(line != ''):

    # Do Something

    line = obj.readline()

Cleanest way to write retry logic?

public void TryThreeTimes(Action action)
{
    var tries = 3;
    while (true) {
        try {
            action();
            break; // success!
        } catch {
            if (--tries == 0)
                throw;
            Thread.Sleep(1000);
        }
    }
}

Then you would call:

TryThreeTimes(DoSomething);

...or alternatively...

TryThreeTimes(() => DoSomethingElse(withLocalVariable));

A more flexible option:

public void DoWithRetry(Action action, TimeSpan sleepPeriod, int tryCount = 3)
{
    if (tryCount <= 0)
        throw new ArgumentOutOfRangeException(nameof(tryCount));

    while (true) {
        try {
            action();
            break; // success!
        } catch {
            if (--tryCount == 0)
                throw;
            Thread.Sleep(sleepPeriod);
        }
   }
}

To be used as:

DoWithRetry(DoSomething, TimeSpan.FromSeconds(2), tryCount: 10);

A more modern version with support for async/await:

public async Task DoWithRetryAsync(Func<Task> action, TimeSpan sleepPeriod, int tryCount = 3)
{
    if (tryCount <= 0)
        throw new ArgumentOutOfRangeException(nameof(tryCount));

    while (true) {
        try {
            await action();
            return; // success!
        } catch {
            if (--tryCount == 0)
                throw;
            await Task.Delay(sleepPeriod);
        }
   }
}

To be used as:

await DoWithRetryAsync(DoSomethingAsync, TimeSpan.FromSeconds(2), tryCount: 10);

Add onclick event to newly added element in JavaScript

In case you do not want to write all the code you have once written in the function you called. Please use the following code, using jQuery:

$(element).on('click', function () { add_img(); });

How to make a loop in x86 assembly language?

You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:

gcd_alg:
    subl    %ecx, %eax      /* a = a - c */
    cmpl    $0, %eax        /* if a == 0 */
    je      gcd_done        /* jump to end */
    cmpl    %ecx, %eax      /* if a < c */
    jl      gcd_preswap     /* swap and start over */
    jmp     gcd_alg         /* keep subtracting */

Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.

As for clearing the screen, that depends on the system you're using.

Checking for NULL pointer in C/C++

I'm a huge fan of the fact that C/C++ doesn't check types in the boolean conditions in if, for and while statements. I always use the following:

if (ptr)

if (!ptr)

even on integers or other type that converts to bool:

while(i--)
{
    // Something to do i times
}

while(cin >> a >> b)
{
    // Do something while you've input
}

Coding in this style is more readable and clearer to me. Just my personal opinion.

Recently, while working on OKI 431 microcontroller, I've noticed that the following:

unsigned char chx;

if (chx) // ...

is more efficient than

if (chx == 1) // ...

because in later case the compiler has to compare the value of chx to 1. Where chx is just a true/false flag.

How to make a checkbox checked with jQuery?

I think you should use prop(), if you are using jQuery 1.6 onwards.

To check it you should do:

$('#test').prop('checked', true);

to uncheck it:

$('#test').prop('checked', false);

Setting up a cron job in Windows

There's pycron which I really as a Cron implementation for windows, but there's also the built in scheduler which should work just fine for what you need (Control Panel -> Scheduled Tasks -> Add Scheduled Task).

Adding line break in C# Code behind page

In C# there's no 'new line' character like there is in VB.NET. The end of a logical 'line' of code is denoted by a ';'. If you wish to break the line of code over multiple lines, just hit the carriage return (or if you want to programmatically add it (for programmatically generated code) insert 'Environment.NewLine' or '\r\n'.

Edit: In response to your comment: If you wish to break a string over multiple lines (i.e. programmatically), you should insert the Environment.NewLine character. This will take the environment into account in order to create the line ending. For instance, many environments, including Unix/Linux only use a NewLine character (\n), but Windows uses both carriage return and line feed (\r\n). So to break a string you would use:

string output = "Hello this is my string\r\nthat I want broken over multiple lines."

Of course, this would only be good for Windows, so before I get flamed for incorrect practice you should actually do this:

string output = string.Format("Hello this is my string{0}that I want broken over multiple lines.", Environment.NewLine);

Or if you want to break over multiple lines in your IDE, you would do:

string output = "My string"
              + "is split over"
              + "multiple lines";

What's the difference between a web site and a web application?

A web application is a website in the same way that a square is a rectangle.

The application part is the model-controller combo. The web part (the view) is why it qualifies as a website.

Something that is only a website and not a web application is simply missing the dynamic aspect.

Of course, it can be difficult to decide on how much server-side processing is required to qualify it as a web application. Probably when it has a data store.

Thus, you have the primary role of webapps confused. A website's primary role is to inform. A web app's primary role is to inform using dynamic content (the do something part).

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Laravel Checking If a Record Exists

$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif

How do you implement a circular buffer in C?

Can you enumerate the types needed at the time you code up the buffer, or do you need to be able to add types at run time via dynamic calls? If the former, then I would create the buffer as a heap-allocated array of n structs, where each struct consists of two elements: an enum tag identifying the data type, and a union of all the data types. What you lose in terms of extra storage for small elements, you make up in terms of not having to deal with allocation/deallocation and the resulting memory fragmentation. Then you just need to keep track of the start and end indices that define the head and tail elements of the buffer, and make sure to compute mod n when incrementing/decrementing the indices.

setTimeout in for-loop does not print consecutive values

ANSWER?

I'm using it for an animation for adding items to a cart - a cart icon floats to the cart area from the product "add" button, when clicked:

function addCartItem(opts) {
    for (var i=0; i<opts.qty; i++) {
        setTimeout(function() {
            console.log('ADDED ONE!');
        }, 1000*i);
    }
};

NOTE the duration is in unit times n epocs.

So starting at the the click moment, the animations start epoc (of EACH animation) is the product of each one-second-unit multiplied by the number of items.

epoc: https://en.wikipedia.org/wiki/Epoch_(reference_date)

Hope this helps!

PHP find difference between two datetimes

Here is my full post with topic: PHP find difference between two datetimes

USAGE EXAMPLE


    echo timeDifference('2016-05-27 02:00:00', 'Y-m-d H:i:s', '2017-08-30 00:01:59', 'Y-m-d H:i:s', false, '%a days %h hours');
    #459 days 22 hours (string)

    echo timeDifference('2016-05-27 02:00:00', 'Y-m-d H:i:s', '2016-05-27 07:00:00', 'Y-m-d H:i:s', true, 'hours',true);
    #-5 (int)

What is the difference between Views and Materialized Views in Oracle?

A view uses a query to pull data from the underlying tables.

A materialized view is a table on disk that contains the result set of a query.

Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH has been in place since at least Oracle 10.

makefile execute another target

If you removed the make all line from your "fresh" target:

fresh :
    rm -f *.o $(EXEC)
    clear

You could simply run the command make fresh all, which will execute as make fresh; make all.

Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.

How to hide output of subprocess in Python 2.7

Why not use commands.getoutput() instead?

import commands

text = "Mario Balotelli" 
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

Fit cell width to content

There are many ways to do this!

correct me if I'm wrong but the question is looking for this kind of result.

<table style="white-space:nowrap;width:100%;">
<tr>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:auto">this should be the content width</td>
</tr>
</table>

The first 2 fields will "share" the remaining page (NOTE: if you add more text to either 50% fields it will take more space), and the last field will dominate the table constantly.

If you are happy to let text wrap you can move white-space:nowrap; to the style of the 3rd field
will be the only way to start a new line in that field.

alternatively, you can set a length on the last field ie. width:150px, and leave percentage's on the first 2 fields.

Hope this helps!

How to create a DataTable in C# and how to add rows?

You can also pass in an object array as well, like so:

DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);

Or even:

dt.Rows.Add(new object[] { "Ravi", 500 });

mysqldump Error 1045 Access denied despite correct passwords etc

Access dined problem solved when I run command prompt in Administrator mode.

Go to Start-> All Programs -> Accessories right click on Command Prompt clickc on Run as.. Select The Following User select administrator username from select option enter password if any click OK button.

Example 1: For entire database backup in mysql using command prompt.

In Windows 7 and 8

C:\Program Files <x86>>\MySQL\MySQL Server 5.5\bin>mysqldump test -u root -p >testDB.sql
Enter Password: *********

In Windows xp

C:\Program Files\MySQL\MySQL Server 5.5\bin>mysqldump test -u root -p >testDB.sql
Enter Password: *********

It asks password for credentials enter password and click on Enter button.

Example 2: For specific table backup / dump in mysql using command prompt.

In Windows 7 and 8

C:\Program Files <x86>>\MySQL\MySQL Server 5.5\bin>mysqldump test -u root -p images>testDB_Images.sql
Enter Password: *********

In Windows xp

C:\Program Files\MySQL\MySQL Server 5.5\bin>mysqldump test -u root -p images>testDB_Images.sql
Enter Password: *********

Dumpt file will be created under folder

In windows xp

C:\Program Files\MySQL\MySQL Server 5.5\bin

In windows 7 and 8

C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin

Note: Check MySQL installation folder in Windows 7, 8 while run in command prompt. If MySQLWorkbench is 32 bit version it is installed in Program Files (x86) folder other wise Program Files folder.

Exception of type 'System.OutOfMemoryException' was thrown.

Running in Debug Mode

When you're developing and debugging an application, you will typically run with the debug attribute in the web.config file set to true and your DLLs compiled in debug mode. However, before you deploy your application to test or to production, you should compile your components in release mode and set the debug attribute to false.

ASP.NET works differently on many levels when running in debug mode. In fact, when you are running in debug mode, the GC will allow your objects to remain alive longer (until the end of the scope) so you will always see higher memory usage when running in debug mode.

Another often unrealized side-effect of running in debug mode is that client scripts served via the webresource.axd and scriptresource.axd handlers will not be cached. That means that each client request will have to download any scripts (such as ASP.NET AJAX scripts) instead of taking advantage of client-side caching. This can lead to a substantial performance hit.

Source: http://blogs.iis.net/webtopics/archive/2009/05/22/troubleshooting-system-outofmemoryexceptions-in-asp-net.aspx

Why is list initialization (using curly braces) better than the alternatives?

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

List initialization does not allow narrowing (§iso.8.5.4). That is:

  • An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char.
  • A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float.
  • A floating-point value cannot be converted to an integer type.
  • An integer value cannot be converted to a floating-point type.

Example:

void fun(double val, int val2) {

    int x2 = val;    // if val == 7.9, x2 becomes 7 (bad)

    char c2 = val2;  // if val2 == 1025, c2 becomes 1 (bad)

    int x3 {val};    // error: possible truncation (good)

    char c3 {val2};  // error: possible narrowing (good)

    char c4 {24};    // OK: 24 can be represented exactly as a char (good)

    char c5 {264};   // error (assuming 8-bit chars): 264 cannot be 
                     // represented as a char (good)

    int x4 {2.0};    // error: no double to int value conversion (good)

}

The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.

Example:

auto z1 {99};   // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99;   // z3 is an int

Conclusion

Prefer {} initialization over alternatives unless you have a strong reason not to.

Laravel password validation rule

This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:

    $inputs = [
        'email'    => 'foo',
        'password' => 'bar',
    ];

    $rules = [
        'email'    => 'required|email',
        'password' => [
            'required',
            'string',
            'min:10',             // must be at least 10 characters in length
            'regex:/[a-z]/',      // must contain at least one lowercase letter
            'regex:/[A-Z]/',      // must contain at least one uppercase letter
            'regex:/[0-9]/',      // must contain at least one digit
            'regex:/[@$!%*#?&]/', // must contain a special character
        ],
    ];

    $validation = \Validator::make( $inputs, $rules );

    if ( $validation->fails() ) {
        print_r( $validation->errors()->all() );
    }

Would output:

    [
        'The email must be a valid email address.',
        'The password must be at least 10 characters.',
        'The password format is invalid.',
    ]

(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)

ListView with Add and Delete Buttons in each Row in android

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I noticed that in the csproj the framework entity had hintpath like

<HintPath>..\..\..\..\..\..\Users\{myusername}

I had this in the nuget.config file:

 <config>
 <add key="repositoryPath" value="../lib" />
 </config>

a) I removed the above lines, b) uninstalled the framework entity package, c) THEN CLOSED THE solution and reopened it, d) reinstalled the framework.

It fixed my issue.

Enabling WiFi on Android Emulator

Wifi is not available on the emulator if you are using below of API level 25.

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

More Information: https://developer.android.com/studio/run/emulator.html#wifi

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

Service Temporarily Unavailable Magento?

Check if there is a file called maintenance.flag and if so delete it.

Magento 1.x : maintenance.flag file is in : magento root directory

Magento 2.x : maintenance.flag file is in : var folder

When Magento is performing certain tasks it temporarily creates this file. Magento checks for its existence and if it's there will send users to the page you described.

It's supposed to automatically delete this file when done processing whatever task it was doing, but I've experienced occasions where something went wrong and it failed to delete it.

How to extract one column of a csv file

I wonder why none of the answers so far have mentioned csvkit.

csvkit is a suite of command-line tools for converting to and working with CSV

csvkit documentation

I use it exclusively for csv data management and so far I have not found a problem that I could not solve using cvskit.

To extract one or more columns from a cvs file you can use the csvcut utility that is part of the toolbox. To extract the second column use this command:

csvcut -c 2 filename_in.csv > filename_out.csv 

csvcut reference page

If the strings in the csv are quoted, add the quote character with the q option:

csvcut -q '"' -c 2 filename_in.csv > filename_out.csv 

Install with pip install csvkit or sudo apt install csvkit.

How do I programmatically set the value of a select box element using JavaScript?

document.getElementById('leaveCode').value = '10';

That should set the selection to "Annual Leave"

String contains another two strings

With the code d.Contains(b + a) you check if "You hit someone for 50 damage" contains "someonedamage". And this (i guess) you don't want.

The + concats the two string of b and a.

You have to check it by

if(d.Contains(b) && d.Contains(a))

Python: Assign print output to a variable

Please note, I wrote this answer based on Python 3.x. No worries you can assign print() statement to the variable like this.

>>> var = print('some text')
some text
>>> var
>>> type(var)
<class 'NoneType'>

According to the documentation,

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

That's why we cannot assign print() statement values to the variable. In this question you have ask (or any function). So print() also a function with the return value with None. So the return value of python function is None. But you can call the function(with parenthesis ()) and save the return value in this way.

>>> var = some_function()

So the var variable has the return value of some_function() or the default value None. According to the documentation about print(), All non-keyword arguments are converted to strings like str() does and written to the stream. Lets look what happen inside the str().

Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.

So we get a string object, then you can modify the below code line as follows,

>>> var = str(some_function())

or you can use str.join() if you really have a string object.

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

change can be as follows,

>>> var = ''.join(some_function())  # you can use this if some_function() really returns a string value

Postgres Error: More than one row returned by a subquery used as an expression

USE LIMIT 1 - so It will return only 1 row. Example

customerId- (select id from enumeration where enumerations.name = 'Ready To Invoice' limit 1)

How to connect to LocalDB in Visual Studio Server Explorer?

The following works with Visual Studio 2017 Community Edition on Windows 10 using SQLServer Express 2016.

Open a PowerShell check what it is called using SqlLocalDB.exe info and whether it is Running with SqlLocalDB.exe info NAME. Here's what it looks like on my machine:

> SqlLocalDB.exe info
MSSQLLocalDB
> SqlLocalDB.exe info MSSQLLocalDB
Name:               mssqllocaldb
Version:            13.0.1601.5
Shared name:
Owner:              DESKTOP-I4H3E09\simon
Auto-create:        Yes
State:              Running
Last start time:    4/12/2017 8:24:36 AM
Instance pipe name: np:\\.\pipe\LOCALDB#EFC58609\tsql\query
>

If it isn't running then you need to start it with SqlLocalDB.exe start MSSQLLocalDB. When it is running you see the Instance pipe name: which starts with np:\\. Copy that named pipe string. Within VS2017 open the view Server Explorer and create a new connection of type Microsoft SQL Server (SqlClient) (don't be fooled by the other file types you want the full fat connection type) and set the Server name: to be the instance pipe name you copied from PowerShell.

I also set the Connect to database to be the same database that was in the connection string that was working in my Dotnet Core / Entity Framework Core project which was set up using dotnet ef database update.

You can login and create a database using the sqlcmd and the named pipe string:

sqlcmd -S np:\\.\pipe\LOCALDB#EFC58609\tsql\query 1> create database EFGetStarted.ConsoleApp.NewDb; 2> GO

There are instructions on how to create a user for your application at https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility

HTML - How to do a Confirmation popup to a Submit button and then send the request?

Another option that you can use is:

onclick="if(confirm('Do you have sure ?')){}else{return false;};"

using this function on submit button you will get what you expect.

AngularJS : Custom filters and ng-repeat

You can call more of 1 function filters in the same ng-repeat filter

<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">

How to find all the subclasses of a class given its name?

Here is a simple but efficient version of code:

def get_all_subclasses(cls):
    subclass_list = []

    def recurse(klass):
        for subclass in klass.__subclasses__():
            subclass_list.append(subclass)
            recurse(subclass)

    recurse(cls)

    return set(subclass_list)

Its time complexity is O(n) where n is the number of all subclasses if there's no multiple inheritance. It's more efficient than the functions that recursively create lists or yield classes with generators, whose complexity could be (1) O(nlogn) when the class hierarchy is a balanced tree or (2) O(n^2) when the class hierarchy is a biased tree.

JPA : How to convert a native query result set to POJO class collection

In hibernate you can use this code to easily map your native query.

private List < Map < String, Object >> getNativeQueryResultInMap() {
String mapQueryStr = "SELECT * FROM AB_SERVICE three ";
Query query = em.createNativeQuery(mapQueryStr);
NativeQueryImpl nativeQuery = (NativeQueryImpl) query;
nativeQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List < Map < String, Object >> result = query.getResultList();
for (Map map: result) {
    System.out.println("after request  ::: " + map);
}
return result;}

Finding element in XDocument?

You can do it this way:

xml.Descendants().SingleOrDefault(p => p.Name.LocalName == "Name of the node to find")

where xml is a XDocument.

Be aware that the property Name returns an object that has a LocalName and a Namespace. That's why you have to use Name.LocalName if you want to compare by name.

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

What I did was I uninstalled Java from my PC, and then downloaded and installed JDK again from Oracle. After this it worked perfectly. I think the problem was because the JRE and JDK update version were different from each other.

Websocket onerror - how to read error description?

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
{
    websocket = new WebSocket("ws://yourDomainNameHere.org/");

    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    };
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See http://tools.ietf.org/html/rfc6455#section-7.4.1
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";

        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    };
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    };
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    };
}
else
{
    alert("Websocket is not supported by your browser");
    return;
}

websocket.send("Yo wazzup");

websocket.close();

See http://jsfiddle.net/gr0bhrqr/

How to skip the first n rows in sql query

In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.

Example:

select * from table order by [some_column] 
offset 10 rows
FETCH NEXT 10 rows only

How to open a PDF file in an <iframe>?

Using an iframe to "render" a PDF will not work on all browsers; it depends on how the browser handles PDF files. Some browsers (such as Firefox and Chrome) have a built-in PDF rendered which allows them to display the PDF inline where as some older browsers (perhaps older versions of IE attempt to download the file instead).

Instead, I recommend checking out PDFObject which is a Javascript library to embed PDFs in HTML files. It handles browser compatibility pretty well and will most likely work on IE8.

In your HTML, you could set up a div to display the PDFs:

<div id="pdfRenderer"></div>

Then, you can have Javascript code to embed a PDF in that div:

var pdf = new PDFObject({
  url: "https://something.com/HTC_One_XL_User_Guide.pdf",
  id: "pdfRendered",
  pdfOpenParams: {
    view: "FitH"
  }
}).embed("pdfRenderer");

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

As the error says your router link should match the existing routes configured

It should be just routerLink="/about"

how to activate a textbox if I select an other option in drop down box

Below is the core JavaScript you need to write:

<html> 
<head>  
<script type="text/javascript">
function CheckColors(val){
 var element=document.getElementById('color');
 if(val=='pick a color'||val=='others')
   element.style.display='block';
 else  
   element.style.display='none';
}

</script> 
</head>
<body>
  <select name="color" onchange='CheckColors(this.value);'> 
    <option>pick a color</option>  
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
  </select>
<input type="text" name="color" id="color" style='display:none;'/>
</body>
</html>

PHP mySQL - Insert new record into table with auto-increment on primary key

You can also use blank single quotes for the auto_increment column. something like this. It worked for me.

$query = "INSERT INTO myTable VALUES ('','Fname', 'Lname', 'Website')";

Add Favicon with React and Webpack

I use favicons-webpack-plugin

const FaviconsWebpackPlugin = require("favicons-webpack-plugin");

module.exports={
plugins:[
    new FaviconsWebpackPlugin("./public/favicon.ico"),
//public is in the root folder in this app. 

]
}

What is define([ , function ]) in JavaScript?

That's probably a requireJS module definition

Check here for more details

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Android device chooser - My device seems offline

I fixed it by deleting unwanted applications/games from my device--make sure there is more than 15mb free space on the device.). It will work :)

-bash: export: `=': not a valid identifier

You cannot put spaces around the = sign when you do:

export foo=bar

Remove the spaces you have and you should be good to go.

If you type:

export foo = bar

the shell will interpret that as a request to export three names: foo, = and bar. = isn't a valid variable name, so the command fails. The variable name, equals sign and it's value must not be separated by spaces for them to be processed as a simultaneous assignment and export.

How to form a correct MySQL connection string?

string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";

How to set upload_max_filesize in .htaccess?

php_value memory_limit 30M
php_value post_max_size 100M
php_value upload_max_filesize 30M

Use all 3 in .htaccess after everything at last line. php_value post_max_size must be more than than the remaining two.

How to force table cell <td> content to wrap?

.wrappable { 
      overflow: hidden; 
      max-width: 400px; 
      word-wrap: break-word; 
}

I have tested with the binary data and its working perfectly here.

Should import statements always be at the top of a module?

This is a fascinating discussion. Like many others I had never even considered this topic. I got cornered into having to have the imports in the functions because of wanting to use the Django ORM in one of my libraries. I was having to call django.setup() before importing my model classes and because this was at the top of the file it was being dragged into completely non-Django library code because of the IoC injector construction.

I kind of hacked around a bit and ended up putting the django.setup() in the singleton constructor and the relevant import at the top of each class method. Now this worked fine but made me uneasy because the imports weren't at the top and also I started worrying about the extra time hit of the imports. Then I came here and read with great interest everybody's take on this.

I have a long C++ background and now use Python/Cython. My take on this is that why not put the imports in the function unless it causes you a profiled bottleneck. It's only like declaring space for variables just before you need them. The trouble is I have thousands of lines of code with all the imports at the top! So I think I will do it from now on and change the odd file here and there when I'm passing through and have the time.

How to properly set Column Width upon creating Excel file? (Column properties)

I normally do this in VB and its easier because Excel records macros in VB. So I normally go to Excel and save the macro I want to do.

So that's what I did now and I got this code:

Columns("E:E").ColumnWidth = 17.29;

Range("E3").Interior.Pattern = xlSolid;
Range("E3").Interior.PatternColorIndex = xlAutomatic;
Range("E3").Interior.Color = 65535;
Range("E3").Interior.TintAndShade = 0;
Range("E3").Interior.PatternTintAndShade = 0;

I think you can do something like this:

xlWorkSheet.Columns[5].ColumnWidth = 18;

For your last question what you need to do is loop trough the columns you want to set their width:

for (int i = 1; i <= 10; i++) // this will apply it from col 1 to 10
{
    xlWorkSheet.Columns[i].ColumnWidth = 18;
}

How do I protect javascript files?

I agree with everyone else here: With JS on the client, the cat is out of the bag and there is nothing completely foolproof that can be done.

Having said that; in some cases I do this to put some hurdles in the way of those who want to take a look at the code. This is how the algorithm works (roughly)

  1. The server creates 3 hashed and salted values. One for the current timestamp, and the other two for each of the next 2 seconds. These values are sent over to the client via Ajax to the client as a comma delimited string; from my PHP module. In some cases, I think you can hard-bake these values into a script section of HTML when the page is formed, and delete that script tag once the use of the hashes is over The server is CORS protected and does all the usual SERVER_NAME etc check (which is not much of a protection but at least provides some modicum of resistance to script kiddies).

  2. Also it would be nice, if the the server checks if there was indeed an authenticated user's client doing this

  3. The client then sends the same 3 hashed values back to the server thru an ajax call to fetch the actual JS that I need. The server checks the hashes against the current time stamp there... The three values ensure that the data is being sent within the 3 second window to account for latency between the browser and the server

  4. The server needs to be convinced that one of the hashes is matched correctly; and if so it would send over the crucial JS back to the client. This is a simple, crude "One time use Password" without the need for any database at the back end.

  5. This means, that any hacker has only the 3 second window period since the generation of the first set of hashes to get to the actual JS code.

  6. The entire client code can be inside an IIFE function so some of the variables inside the client are even more harder to read from the Inspector console

    This is not any deep solution: A determined hacker can register, get an account and then ask the server to generate the first three hashes; by doing tricks to go around Ajax and CORS; and then make the client perform the second call to get to the actual code -- but it is a reasonable amount of work.

Moreover, if the Salt used by the server is based on the login credentials; the server may be able to detect who is that user who tried to retreive the sensitive JS (The server needs to do some more additional work regarding the behaviour of the user AFTER the sensitive JS was retreived, and block the person if the person, say for example, did not do some other activity which was expected)

An old, crude version of this was done for a hackathon here: http://planwithin.com/demo/tadr.html That wil not work in case the server detects too much latency, and it goes beyond the 3 second window period

How can I create a simple message box in Python?

Have you looked at easygui?

import easygui

easygui.msgbox("This is a message!", title="simple gui")

What is a .NET developer?

I'd say the minimum would be to

  • know one of the .Net Languages (C#, VB.NET, etc.)
  • know the basic working of the .Net runtime
  • know and understand the core parts of the .Net class libraries
  • have an understanding about what additional classes and functions are available as part of the .Net class libraries

Creating a ZIP archive in memory using System.IO.Compression

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program`enter code here`
    {
        static void Main(string[] args)
        {
            using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                            writer.WriteLine("Information about this package.");
                            writer.WriteLine("========================");
                    }
                }
            }
        }
    }
}

Custom Date Format for Bootstrap-DatePicker

I'm sure you are using a old version. You must use the last version available at master branch:

https://github.com/eternicode/bootstrap-datepicker

Java error: Implicit super constructor is undefined for default constructor

You get this error because a class which has no constructor has a default constructor, which is argument-less and is equivalent to the following code:

public ACSubClass() {
    super();
}

However since your BaseClass declares a constructor (and therefore doesn't have the default, no-arg constructor that the compiler would otherwise provide) this is illegal - a class that extends BaseClass can't call super(); because there is not a no-argument constructor in BaseClass.

This is probably a little counter-intuitive because you might think that a subclass automatically has any constructor that the base class has.

The simplest way around this is for the base class to not declare a constructor (and thus have the default, no-arg constructor) or have a declared no-arg constructor (either by itself or alongside any other constructors). But often this approach can't be applied - because you need whatever arguments are being passed into the constructor to construct a legit instance of the class.

How do you change the document font in LaTeX?

For a different approach, I would suggest using the XeTeX or LuaTex system. They allow you to access system fonts (TrueType, OpenType, etc) and set font features. In a typical LaTeX document, you just need to include this in your headers:

\usepackage{fontspec}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont{Times}
\setmonofont{Lucida Sans Typewriter}

It's the fontspec package that allows for \setmainfont and \setmonofont. The ability to choose a multitude of font features is beyond my expertise, but I would suggest looking up some examples and seeing if this would suit your needs.

Just don't forget to replace your favorite latex compiler by the appropriate one (xelatex or lualatex).

unable to start mongodb local server

Don't kill the process using the -9 signal as it would cause damage: http://www.mongodb.org/display/DOCS/Starting+and+Stopping+Mongo#StartingandStoppingMongo-SendingaUnixINTorTERMsignal

Use sudo killall -15 mongod instead

Taking inputs with BufferedReader in Java

The problem id because of inp.read(); method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.

What you can do simply

for(int i=0;i<T;i++) {
    String s= inp.readLine();
    String[] intValues = inp.readLine().split(" ");
    int[] m= new int[2];
    m[0]=Integer.parseInt(intValues[0]);
    m[1]=Integer.parseInt(intValues[1]);

    // Checking whether I am taking the inputs correctly
    System.out.println(s);
    System.out.println(m[0]);
    System.out.println(m[1]);
}

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the minimum version of the Android operating system required to run your application.

The target sdk version is the version of Android that your app was created to run on.

The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.

Usually the compile sdk version and the target sdk version are the same.

How to set the font size in Emacs?

I've got the following in my .emacs:

(defun fontify-frame (frame)
  (set-frame-parameter frame 'font "Monospace-11"))

;; Fontify current frame
(fontify-frame nil)
;; Fontify any future frames
(push 'fontify-frame after-make-frame-functions) 

You can subsitute any font of your choosing for "Monospace-11". The set of available options is highly system-dependent. Using M-x set-default-font and looking at the tab-completions will give you some ideas. On my system, with Emacs 23 and anti-aliasing enabled, can choose system fonts by name, e.g., Monospace, Sans Serif, etc.

HTML5 and frameborder

style="border:none; scrolling:no; frameborder:0;  marginheight:0; marginwidth:0; "

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

How to clamp an integer to some range?

This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them.

new_index = max(0, min(new_index, len(mylist)-1))

How can I manually generate a .pyc file from a .py file

I found several ways to compile python scripts into bytecode

  1. Using py_compile in terminal:

    python -m py_compile File1.py File2.py File3.py ...
    

    -m specifies the module(s) name to be compiled.

    Or, for interactive compilation of files

    python -m py_compile -
    File1.py
    File2.py
    File3.py
       .
       .
       .
    
  2. Using py_compile.compile:

    import py_compile
    py_compile.compile('YourFileName.py')
    
  3. Using py_compile.main():

    It compiles several files at a time.

    import py_compile
    py_compile.main(['File1.py','File2.py','File3.py'])
    

    The list can grow as long as you wish. Alternatively, you can obviously pass a list of files in main or even file names in command line args.

    Or, if you pass ['-'] in main then it can compile files interactively.

  4. Using compileall.compile_dir():

    import compileall
    compileall.compile_dir(direname)
    

    It compiles every single Python file present in the supplied directory.

  5. Using compileall.compile_file():

    import compileall
    compileall.compile_file('YourFileName.py')
    

Take a look at the links below:

https://docs.python.org/3/library/py_compile.html

https://docs.python.org/3/library/compileall.html

How do I check if the Java JDK is installed on Mac?

  • Open terminal.
  • run command to see:

    javac -version

  • Also you can verify manually by going to the specific location and then check. To do this run below command in the mac terminal

    cd /Library/Java/JavaVirtualMachines/

Then run ls command in the terminal again. Now you can see the jdk version & package if exists in your computer.

In vb.net, how to get the column names from a datatable

You can loop through the columns collection of the datatable.

VB

Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
    Console.WriteLine(column.ColumnName)
Next

C#

DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}

Hope this helps!

Storing Images in DB - Yea or Nay?

Your web-server (I'm assuming you are using one) is designed to handle images while a database is not. Thus I would vote heavily on the nay side.

Store just the path (and maybe file info too) in the database.

How to get an IFrame to be responsive in iOS Safari?

CSS only solution

HTML

<div class="container">
    <div class="h_iframe">
        <iframe  src="//www.youtube.com/embed/9KunP3sZyI0" frameborder="0" allowfullscreen></iframe>
    </div>
</div>

CSS

html,body {
    height:100%;
}
.h_iframe iframe {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}

DEMO

Another demo here with HTML page in iframe

Signing a Windows EXE file

You can get a free cheap code signing certificate from Certum if you're doing open source development.

I've been using their certificate for over a year, and it does get rid of the unknown publisher message from Windows.

As far as signing code I use signtool.exe from a script like this:

signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll /f "MyCert.pfx" /p MyPassword /d SignedFile.exe SignedFile.exe

Convert string to number and add one

Have you tried flip-flopping it a bit?

var newcurrentpageTemp = parseInt($(this).attr("id"));
newcurrentpageTemp++;
alert(newcurrentpageTemp));

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

@Blorgbeard:

New Features in C99

  • inline functions
  • variable declaration no longer restricted to file scope or the start of a compound statement
  • several new data types, including long long int, optional extended integer types, an explicit boolean data type, and a complex type to represent complex numbers
  • variable-length arrays
  • support for one-line comments beginning with //, as in BCPL or C++
  • new library functions, such as snprintf
  • new header files, such as stdbool.h and inttypes.h
  • type-generic math functions (tgmath.h)
  • improved support for IEEE floating point
  • designated initializers
  • compound literals
  • support for variadic macros (macros of variable arity)
  • restrict qualification to allow more aggressive code optimization

http://en.wikipedia.org/wiki/C99

A Tour of C99

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

There is now a new way of addressing this issue - if you remove position: relative from the container which needs to have the overflow-y visible, you can have overflow-y visible and overflow-x hidden, and vice versa (have overflow-x visible and overflow-y hidden, just make sure the container with the visible property is not relatively positioned).

See this post from CSS Tricks for more details - it worked for me: https://css-tricks.com/popping-hidden-overflow/

How to add google-play-services.jar project dependency so my project will run and present map

The quick start guide that keyboardsurfer references will work if you need to get your project to build properly, but it leaves you with a dummy google-play-services project in your Eclipse workspace, and it doesn't properly link Eclipse to the Google Play Services Javadocs.

Here's what I did instead:

  1. Install the Google Play Services SDK using the instructions in the Android Maps V2 Quick Start referenced above, or the instructions to Setup Google Play Services SDK, but do not follow the instructions to add Google Play Services into your project.

  2. Right click on the project in the Package Explorer, select Properties to open the properties for your project.

  3. (Only if you already followed the instructions in the quick start guide!) Remove the dependency on the google-play-services project:

    • Click on the Android category and remove the reference to the google-play-services project.

    • Click on the Java Build Path category, then the Projects tab and remove the reference to the google-play-services project.

  4. Click on the Java Build Path category, then the Libraries tab.

  5. Click Add External JARs... and select the google-play-services.jar file. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\libproject\google-play-services_lib\libs.

  6. Click on the arrow next to the new google-play-services.jar entry, and select the Javadoc Location item.

  7. Click Edit... and select the folder containing the Google Play Services Javadocs. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\docs\reference.

  8. Still in the Java Build Path category, click on the Order and Export tab. Check the box next to the google-play-services.jar entry.

  9. Click OK to save your project properties.

Your project should now have access to the Google Play Services library, and the Javadocs should display properly in Eclipse.

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

The issue I was facing was I have a project that is dependent on a library project. In order to build I was following these steps:

msbuild.exe myproject.vbproj /T:Rebuild
msbuild.exe myproject.vbproj /T:Package

That of course meant I was missing my library's dll files in bin and most importantly in the package zip file. I found this works perfectly:

msbuild.exe myproject.vbproj /T:Rebuild;Package

I have no idea why this work or why it didn't in the first place. But hope that helps.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

Add Json NamingStrategy property to your class definition.

_x000D_
_x000D_
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
_x000D_
_x000D_
_x000D_

Get values from label using jQuery

Firstly, I don't think spaces for an id is valid.

So i'd change the id to not include spaces.

<label year="2010" month="6" id="currentMonth"> June &nbsp;2010</label>

then the jquery code is simple (keep in mind, its better to fetch the jquery object once and use over and over agian)

var label = $('#currentMonth');
var month = label.attr('month');
var year = label.attr('year');
var text = label.text();

Postgres: clear entire database before re-creating / re-populating from bash script

Although the following line is taken from a windows batch script, the command should be quite similar:

psql -U username -h localhost -d postgres -c "DROP DATABASE \"$DATABASE\";"

This command is used to clear the whole database, by actually dropping it. The $DATABASE (in Windows should be %DATABASE%) in the command is a windows style environment variable that evaluates to the database name. You will need to substitute that by your development_db_name.

How to set "style=display:none;" using jQuery's attr method?

You can use the hide and show functions of jquery. Examples

In your case just set $('#msform').hide() or $('#msform').show()

Jackson with JSON: Unrecognized field, not marked as ignorable

This just perfectly worked for me

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(
    DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

@JsonIgnoreProperties(ignoreUnknown = true) annotation did not.

How to add an action to a UIAlertView button using Swift iOS

See my code:

 @IBAction func foundclicked(sender: AnyObject) {

            if (amountTF.text.isEmpty)
            {
                let alert = UIAlertView(title: "Oops! Empty Field", message: "Please enter the amount", delegate: nil, cancelButtonTitle: "OK")

                alert.show()
            }

            else {

            var alertController = UIAlertController(title: "Confirm Bid Amount", message: "Final Bid Amount : "+amountTF.text , preferredStyle: .Alert)
            var okAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default) {
                UIAlertAction in

                JHProgressHUD.sharedHUD.loaderColor = UIColor.redColor()
                        JHProgressHUD.sharedHUD.showInView(self.view, withHeader: "Amount registering" , andFooter: "Loading")
                }
            var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
                UIAlertAction in

                alertController .removeFromParentViewController()
            }
                            alertController.addAction(okAction)
                            alertController.addAction(cancelAction)

                self.presentViewController(alertController, animated: true, completion: nil)

            }

        }

Build error, This project references NuGet

First I would check if your MusicKarma project has Microsoft.Net.Compilers in its packages.config file. If not then you could remove everything to do with that NuGet package from your MusicKarma.csproj.

If you are using the Microsoft.Net.Compilers NuGet package then my guess is that the path is incorrect. Looking at the directory name in the error message I would guess that the MusicKarma solution file (.sln) is in the same directory as the MusicKarma.csproj. If so then the packages directory is probably wrong since by default the packages directory would be inside the solution directory. So I am assuming that your packages directory is:

C:\Users\Bryan\Documents\Visual Studio 2015\Projects\MusicKarma\packages

Whilst your MusicKarma.csproj file is looking for the props file in:

C:\Users\Bryan\Documents\Visual Studio 2015\Projects\packages\Microsoft.Net.Compilers.1.1.1\build

So if that is the case then you can fix the problem by editing the path in your MusicKarma.csproj file or by reinstalling the NuGet package.

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

How do I generate random integers within a specific range in Java?

I will simply state what is wrong with the solutions provided by the question and why the errors.

Solution 1:

randomNum = minimum + (int)(Math.random()*maximum); 

Problem: randomNum is assigned values numbers bigger than maximum.

Explanation: Suppose our minimum is 5, and your maximum is 10. Any value from Math.random() greater than 0.6 will make the expression evaluate to 6 or greater, and adding 5 makes it greater than 10 (your maximum). The problem is you are multiplying the random number by the maximum (which generates a number almost as big as the maximum) and then adding the minimum. Unless the minimum is 1, it's not correct. You have to switch to, as mentioned in other answers

randomNum = minimum + (int)(Math.random()*(maximum-minimum+1))

The +1 is because Math.random() will never return 1.0.

Solution 2:

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;

Your problem here is that '%' may return a negative number if the first term is smaller than 0. Since rn.nextInt() returns negative values with ~50% chance, you will also not get the expected result.

This, was, however, almost perfect. You just had to look a bit further down the Javadoc, nextInt(int n). With that method available, doing

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt(n);
randomNum =  minimum + i;

Would also return the desired result.

How can I create an observable with a delay

It's little late to answer ... but just in case may be someone return to this question looking for an answer

'delay' is property(function) of an Observable

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
}).delay(3000);

This worked for me ...

Easy way to make a confirmation dialog in Angular?

Adding more options to the answer.

You could use npm i sweetalert2

Don't forget to add the style to your angular.json

"styles": [
         ...
          "node_modules/sweetalert2/src/sweetalert2.scss"
          ]

Then just import,

// ES6 Modules or TypeScript
import Swal from 'sweetalert2'


// CommonJS
const Swal = require('sweetalert2')

Boom, you are ready to go.

Swal.fire({
  title: 'Are you sure?',
  text: 'You will not be able to recover this imaginary file!',
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete it!',
  cancelButtonText: 'No, keep it'
}).then((result) => {
  if (result.value) {
    Swal.fire(
      'Deleted!',
      'Your imaginary file has been deleted.',
      'success'
    )
  // For more information about handling dismissals please visit
  // https://sweetalert2.github.io/#handling-dismissals
  } else if (result.dismiss === Swal.DismissReason.cancel) {
    Swal.fire(
      'Cancelled',
      'Your imaginary file is safe :)',
      'error'
    )
  }
})

More on this:- https://www.npmjs.com/package/sweetalert2

I do hope this helps someone.

Thanks.

Make REST API call in Swift

You can do like this :

var url : String = "http://google.com?test=toto&test2=titi"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

    if (jsonResult != nil) {
        // process jsonResult
    } else {
       // couldn't load JSON, look at error
    }


})

EDIT : For people have problem with this maybe your JSON stream is an array [] and not an object {} so you have to change jsonResult to NSArray instead of NSDictionary

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

npm not working after clearing cache

I try to

npm cache clean 

But npm said newer version on npm (> 5) has self healing Mechanism and every thing i need to do for checking npm is use verify

npm cache verify

npm message :

The npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. 

If you want to make sure everything is consistent, use 'npm cache verify' instead.

but for forcing npm use this:

npm cache clean --force

Height equal to dynamic width (CSS fluid layout)

Simple and neet : use vw units for a responsive height/width according to the viewport width.

vw : 1/100th of the width of the viewport. (Source MDN)

DEMO

HTML:

<div></div>

CSS for a 1:1 aspect ratio:

div{
    width:80vw;
    height:80vw; /* same as width */
}

Table to calculate height according to the desired aspect ratio and width of element.

   aspect ratio  |  multiply width by
    -----------------------------------
         1:1      |         1
         1:3      |         3
         4:3      |        0.75
        16:9      |       0.5625

This technique allows you to :

  • insert any content inside the element without using position:absolute;
  • no unecessary HTML markup (only one element)
  • adapt the elements aspect ratio according to the height of the viewport using vh units
  • you can make a responsive square or other aspect ratio that alway fits in viewport according to the height and width of the viewport (see this answer : Responsive square according to width and height of viewport or this demo)

These units are supported by IE9+ see canIuse for more info

Correct format specifier to print pointer or address?

As an alternative to the other (very good) answers, you could cast to uintptr_t or intptr_t (from stdint.h/inttypes.h) and use the corresponding integer conversion specifiers. This would allow more flexibility in how the pointer is formatted, but strictly speaking an implementation is not required to provide these typedefs.

Ruby: character to ascii from a string

puts "string".split('').map(&:ord).to_s

Could not find a version that satisfies the requirement tensorflow

Running this before the tensorflow installation solved it for me:

pip install "pip>=19"

As the tensorflow's system requirements states:

pip 19.0 or later

Best way to reset an Oracle sequence to the next value in an existing column?

With oracle 10.2g:

select  level, sequence.NEXTVAL
from  dual 
connect by level <= (select max(pk) from tbl);

will set the current sequence value to the max(pk) of your table (i.e. the next call to NEXTVAL will give you the right result); if you use Toad, press F5 to run the statement, not F9, which pages the output (thus stopping the increment after, usually, 500 rows). Good side: this solution is only DML, not DDL. Only SQL and no PL-SQL. Bad side : this solution prints max(pk) rows of output, i.e. is usually slower than the ALTER SEQUENCE solution.

Google Map API - Removing Markers

Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.

export default function useGoogleMapMarker(props) {
  const [marker, setMarker] = useState();

  useEffect(() => {
    // ...code
    const marker = new maps.Marker({ position, map, title, icon });
    // ...code
    setMarker(marker);
    return () => marker.setMap(null); // to remove markers when unmounts
  }, []);

  return marker;
}

How to count number of unique values of a field in a tab-delimited text file?

Here is a bash script that fully answers the (revised) original question. That is, given any .tsv file, it provides the synopsis for each of the columns in turn. Apart from bash itself, it only uses standard *ix/Mac tools: sed tr wc cut sort uniq.

#!/bin/bash
# Syntax: $0 filename   
# The input is assumed to be a .tsv file

FILE="$1"

cols=$(sed -n 1p $FILE | tr -cd '\t' | wc -c)
cols=$((cols + 2 ))
i=0
for ((i=1; i < $cols; i++))
do
  echo Column $i ::
  cut -f $i < "$FILE" | sort | uniq -c
  echo
done

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

" netsh wlan start hostednetwork " command not working no matter what I try

This was a real issue for me, and quite a sneaky problem to try and remedy...

The problem I had was that a module that was installed on my WiFi adapter was conflicting with the Microsoft Virtual Adapter (or whatever it's actually called).

To fix it:

  1. Hold the Windows Key + Push R
  2. Type: ncpa.cpl in to the box, and hit OK.
  3. Identify the network adapter you want to use for the hostednetwork, right-click it, and select Properties.
  4. You'll see a big box in the middle of the properties window, under the heading The connection uses the following items:. Look down the list for anything that seems out of the ordinary, and uncheck it. Hit OK.
  5. Try running the netsh wlan start hostednetwork command again.
  6. Repeat steps 4 and 5 as necessary.

In my case my adapter was running a module called SoftEther Lightweight Network Protocol, which I believe is used to help connect to VPN Gate VPN servers via the SoftEther software.

If literally nothing else works, then I'd suspect something similar to the problem I encountered, namely that a module on your network adapter is interfering with the hostednetwork aspect of your driver.

How to give a user only select permission on a database

For the GUI minded people, you can:

  • Right click the Database in Management Studio.
  • Choose Properties
  • Select Permissions
  • If your user does not show up in the list, choose Search and type their name
  • Select the user in the Users or Roles list
  • In the lower window frame, Check the Select permission under the Grant column

What is the main purpose of setTag() getTag() methods of View?

I'd like to add few words.

Although using get/setTag(Object) seems to be very useful in the particular case of a ViewHolder pattern, I'd recommend to think twice before using it in other cases. There is almost always another solution with better design.

The main reason is that code like that becomes unsupportable pretty quickly.

  • It is non-obvious for other developers what you designed to store as tag in the view. The methods setTag/getTag are not descriptive at all.

  • It just stores an Object, which requires to be cast when you want to getTag. You can get unexpected crashes later when you decide to change the type of stored object in the tag.

  • Here's a real-life story: We had a pretty big project with a lot of adapters, async operations with views and so on. One developer decided to set/getTag in his part of code, but another one had already set the tag to this view. In the end, someone couldn't find his own tag and was very confused. It cost us several hours to find the bug.

setTag(int key, Object tag) looks much better, cause you can generate unique keys for every tag (using id resources), but there is a significant restriction for Android < 4.0. From Lint docs:

Prior to Android 4.0, the implementation of View.setTag(int, Object) would store the objects in a static map, where the values were strongly referenced. This means that if the object contains any references pointing back to the context, the context (which points to pretty much everything else) will leak. If you pass a view, the view provides a reference to the context that created it. Similarly, view holders typically contain a view, and cursors are sometimes also associated with views.

What USB driver should we use for the Nexus 5?

I am on Windows 8.1, and I tried everything from the other answers and nothing worked. Finally, I decided to try "Pick from a list of drivers" and found "LGE Mobile Sooner Single ADB Interface" under "ADB Interface". ADB.exe was finally able to find the Nexus 5 and sideload 4.4.1.

I hope this helps.

Determining whether an object is a member of a collection in VBA

I wrote this code. I guess it can help someone...

Public Function VerifyCollection()
    For i = 1 To 10 Step 1
       MyKey = "A"
       On Error GoTo KillError:
       Dispersao.Add 1, MyKey
       GoTo KeepInForLoop
KillError: 'If My collection already has the key A Then...
        count = Dispersao(MyKey)
        Dispersao.Remove (MyKey)
        Dispersao.Add count + 1, MyKey 'Increase the amount in relationship with my Key
        count = Dispersao(MyKey) 'count = new amount
        On Error GoTo -1
KeepInForLoop:
    Next
End Function

How do I code my submit button go to an email address

There are several ways to do an email from HTML. Typically you see people doing a mailto like so:

<a href="mailto:[email protected]">Click to email</a>

But if you are doing it from a button you may want to look into a javascript solution.

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Use of *args and **kwargs

You can have a look at python docs (docs.python.org in the FAQ), but more specifically for a good explanation the mysterious miss args and mister kwargs (courtesy of archive.org) (the original, dead link is here).

In a nutshell, both are used when optional parameters to a function or method are used. As Dave says, *args is used when you don't know how many arguments may be passed, and **kwargs when you want to handle parameters specified by name and value as in:

myfunction(myarg=1)

ScrollTo function in AngularJS

Thanks Andy for the example, this was very helpful. I ended implementing a slightly different strategy since I am developing a single-page scroll and did not want Angular to refresh when using the hashbang URL. I also want to preserve the back/forward action of the browser.

Instead of using the directive and the hash, I am using a $scope.$watch on the $location.search, and obtaining the target from there. This gives a nice clean anchor tag

<a ng-href="#/?scroll=myElement">My element</a>

I chained the watch code to the my module declaration in app.js like so:

.run(function($location, $rootScope) {
   $rootScope.$watch(function() { return $location.search() }, function(search) { 
     var scrollPos = 0;
     if (search.hasOwnProperty('scroll')) {
       var $target = $('#' + search.scroll);
       scrollPos = $target.offset().top;
     }   
     $("body,html").animate({scrollTop: scrollPos}, "slow");
   });
})

The caveat with the code above is that if you access by URL directly from a different route, the DOM may not be loaded in time for jQuery's $target.offset() call. The solution is to nest this code within a $viewContentLoaded watcher. The final code looks something like this:

.run(function($location, $rootScope) {
  $rootScope.$on('$viewContentLoaded', function() {
     $rootScope.$watch(function() { return $location.search() }, function(search) {
       var scrollPos = 0 
       if (search.hasOwnProperty('scroll')) {
         var $target = $('#' + search.scroll);
         var scrollPos = $target.offset().top;
       }
       $("body,html").animate({scrollTop: scrollPos}, "slow");                                                                                                                                                                    
     });  
   });    
 })

Tested with Chrome and FF

Section vs Article HTML5

My interpretation is: I think of YouTube it has a comment-section, and inside the comment-section there are multiple articles (in this case comments).

So a section is like a div-container that holds articles.

How to combine class and ID in CSS selector?

Ids are supposed to be unique document wide, so you shouldn't have to select based on both. You can assign an element multiple classes though with class="class1 class2"

Vertically aligning text next to a radio button

simple and short solution add below style:

style="vertical-align: text-bottom;"

Change Git repository directory location.

This did not work for me. I moved a repo from (e.g.) c:\project1\ to c:\repo\project1\ and Git for windows does not show any changes.

git status shows an error because one of the submodules "is not a git repository" and shows the old path. e.g. (names changed to protect IP)

fatal: Not a git repository: C:/project1/.git/modules/subproject/subproject2 fatal: 'git status --porcelain' failed in submodule subproject

I had to manually edit the .git files in the submodules to point to the correct relative path to the submodule's repo (in the main repo's .git/modules directory)

join on multiple columns

Agree no matches in your example.
If you mean both columns on either then need a query like this or need to re-examine the data design.

    Select TableA.Col1, TableA.Col2, TableB.Val
    FROM TableA
    INNER JOIN TableB
          ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2 
          OR TableA.Col2 = TableB.Col1 OR TableA.Col1 = TableB.Col2

Save bitmap to file function

  1. You need an appropriate permission in manifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  2. out.flush() check the out is not null..

  3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                                "/PhysicsSketchpad";
    File dir = new File(file_path);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dir, "sketchpad" + pad.t_id + ".png");
    FileOutputStream fOut = new FileOutputStream(file);
    
    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
    

What is the most efficient way to get first and last line of a text file?

First open the file in read mode.Then use readlines() method to read line by line.All the lines stored in a list.Now you can use list slices to get first and last lines of the file.

    a=open('file.txt','rb')
    lines = a.readlines()
    if lines:
        first_line = lines[:1]
        last_line = lines[-1]

jQuery find element by data attribute value

I searched for a the same solution with a variable instead of the String.
I hope i can help someone with my solution :)

var numb = "3";
$(`#myid[data-tab-id=${numb}]`);

What does the "+" (plus sign) CSS selector mean?

The Plus (+) will select the first immediate element. When you use + selector you have to give two parameters. This will be more clear by example: here div and span are parameters, so in this case only first span after the div will be styled.

 div+ span{
   color: green;
   padding :100px;
}

     <div>The top or first element  </div>
       <span >this is span immediately after div, this will be selected</span>
       <span>This will not be selected</span>

Above style will only apply to first span after div. It is important to note that second span will not be selected.

How to set headers in http get request?

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

Using the GET parameter of a URL in JavaScript

This looked ok:

function gup( name ){
   name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
   var regexS = "[\\?&]"+name+"=([^&#]*)";
   var regex = new RegExp( regexS );
   var results = regex.exec( window.location.href );
   if( results == null )
      return "";
   else
      return results[1];
}

From http://www.netlobo.com/url_query_string_javascript.html

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

How to use a calculated column to calculate another column in the same view

In Sql Server

You can do this using cross apply

Select
  ColumnA,
  ColumnB,
  c.calccolumn1 As calccolumn1,
  c.calccolumn1 / ColumnC As calccolumn2
from t42
cross apply (select (ColumnA + ColumnB) as calccolumn1) as c

Unable to cast object of type 'System.DBNull' to type 'System.String`

ExecuteScalar will return

  • null if there is no result set
  • otherwise the first column of the first row of the resultset, which may be DBNull.

If you know that the first column of the resultset is a string, then to cover all bases you need to check for both null and DBNull. Something like:

object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null) ? String.Empty : accountNumber.ToString();

The above code relies on the fact that DBNull.ToString returns an empty string.

If accountNumber was another type (say integer), then you'd need to be more explicit:

object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null || Convert.IsDBNull(accountNumber) ?     
         (int) accountNumber : 0;

If you know for sure that your resultset will always have at least one row (e.g. SELECT COUNT(*)...), then you can skip the check for null.

In your case the error message "Unable to cast object of type ‘System.DBNull’ to type ‘System.String`" indicates that the first column of your result set is a DBNUll value. This is from the cast to string on the first line:

string accountNumber = (string) ... ExecuteScalar(...);

Marc_s's comment that you don't need to check for DBNull.Value is wrong.

How do I find the version of Apache running without access to the command line?

Warning, some Apache servers do not always send their version number when using HEAD, like in this case:

HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 13:09:45 GMT
Server: Apache
X-Powered-By: PHP/5.2.6RC4-pl0-gentoo
Set-Cookie: PHPSESSID=a97a60f86539b5502ad1109f6759585c; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Connection: close
Content-Type: text/html



Connection to host lost.

If PHP is installed then indeed, just use the php info command:

<?php phpinfo(); ?>

How do I use a char as the case in a switch-case?

public class SwitCase {
    public static void main (String[] args){
        String hello = JOptionPane.showInputDialog("Input a letter: ");
        char hi = hello.charAt(0); //get the first char.
        switch(hi){
            case 'a': System.out.println("a");
        }
    }   
}

Update statement with inner join on Oracle

Do not use some of the answers above.

Some suggest the use of nested SELECT, don't do that, it is excruciatingly slow. If you have lots of records to update, use join, so something like:

update (select bonus 
        from employee_bonus b 
        inner join employees e on b.employee_id = e.employee_id 
        where e.bonus_eligible = 'N') t
set t.bonus = 0;

See this link for more details. http://geekswithblogs.net/WillSmith/archive/2008/06/18/oracle-update-with-join-again.aspx.

Also, ensure that there are primary keys on all the tables you are joining.

Escape regex special characters in a Python string

Use repr()[1:-1]. In this case, the double quotes don't need to be escaped. The [-1:1] slice is to remove the single quote from the beginning and the end.

>>> x = raw_input()
I'm "stuck" :\
>>> print x
I'm "stuck" :\
>>> print repr(x)[1:-1]
I\'m "stuck" :\\

Or maybe you just want to escape a phrase to paste into your program? If so, do this:

>>> raw_input()
I'm "stuck" :\
'I\'m "stuck" :\\'

Converting Numpy Array to OpenCV Array

The simplest solution would be to use Pillow lib:

from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.

adding onclick event to dynamically added button?

Try this:

var inputTag = document.createElement("div");              
inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";    
document.body.appendChild(inputTag);

This creates a button inside a DIV which works perfectly!

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

function solution(s) {
var c = s[0];

if (c == c.toUpperCase() && !(c >= '0' && c <= '9') &&(c >='A' && c <= 'Z')) {
    return 'upper';
} else if (c == c.toLowerCase() && !(c >= '0' && c <= '9') &&(c >='a' && c <= 'z')){
    return 'lower';
} else if (c >= '0' && c <= '9'){
   return 'digit'
} else {
  return 'other' 
}
}

var str1= (solution('A')) // upper
var str2 = solution('b') // lower
var str3 = solution('1') // digit
var str4 = solution('_') // other
console.log(`${str1} ${str2} ${str3} ${str4}`)

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

I'm not exactly sure what it is that you want. Do you want a TimeStamp? Then you can do something simple like:

TimeStamp ts = TimeStamp.FromTicks(value.ToUniversalTime().Ticks);

Since you named a variable epoch, do you want the Unix time equivalent of your date?

DateTime unixStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
long epoch = (long)Math.Floor((value.ToUniversalTime() - unixStart).TotalSeconds);

SOAP client in .NET - references or examples?

I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.

That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):

  • Go ahead and do code-first to create your initial WSDL. Then, delete your code and re-generate the server class(es) from the WSDL. Almost every platform has a tool for this. This will show you what odd habits your particular platform has, and you can begin tweaking the WSDL to be simpler and more straightforward. Tweak, re-gen, repeat. You'll learn a lot this way, and it's portable knowledge.
  • Stick to plain old language classes (POCO, POJO, etc.) for complex types. Do NOT use platform-specific constructs like List<> or DataTable. Even PHP associative arrays will appear to work but fail in ways that are difficult to debug across platforms.
  • Stick to basic data types: bool, int, float, string, date(Time), and arrays. Odds are, the more particular you get about a data type, the less agile you'll be to new requirements over time. You do NOT want to change your WSDL if you can avoid it.
  • One exception to the data types above - give yourself a NameValuePair mechanism of some kind. You wouldn't believe how many times a list of these things will save your bacon in terms of flexibility.
  • Set a real namespace for your WSDL. It's not hard, but you might not believe how many web services I've seen in namespace "http://www.tempuri.org". Also, use a URN ("urn:com-myweb-servicename-v1", not a URL-based namespace ("http://servicename.myweb.com/v1". It's not a website, it's an abstract set of characters that defines a logical grouping. I've probably had a dozen people call me for support and say they went to the "website" and it didn't work.

</rant> :)

wget/curl large file from google drive

You just need to use wget with:

 https://drive.google.com/uc?authuser=0&id=[your ID without brackets]&export=download

PD. The file must be public.

How do I lowercase a string in Python?

Don't try this, totally un-recommend, don't do this:

import string
s='ABCD'
print(''.join([string.ascii_lowercase[string.ascii_uppercase.index(i)] for i in s]))

Output:

abcd

Since no one wrote it yet you can use swapcase (so uppercase letters will become lowercase, and vice versa) (and this one you should use in cases where i just mentioned (convert upper to lower, lower to upper)):

s='ABCD'
print(s.swapcase())

Output:

abcd

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

Convert string to symbol-able in ruby

In Rails you can do this using underscore method:

"Book Author Title".delete(' ').underscore.to_sym
=> :book_author_title

The simpler code is using regex (works with Ruby):

"Book Author Title".downcase.gsub(/\s+/, "_").to_sym
=> :book_author_title

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

EDIT :
http://codepen.io/gcyrillus/pen/daCyu So for a popup, you have to use position:fixed , display:table property and max-width with em or rem values :)
with this CSS basis :

#popup {
  position:fixed;
  width:100%;
  height:100%;
  display:table;
  pointer-events:none;
}
#popup > div {
  display:table-cell;
  vertical-align:middle;
}
#popup p {
  width:80%;
  max-width:20em;
  margin:auto;
  pointer-events:auto;
}

Copy a file in a sane, safe and efficient way

Qt has a method for copying files:

#include <QFile>
QFile::copy("originalFile.example","copiedFile.example");

Note that to use this you have to install Qt (instructions here) and include it in your project (if you're using Windows and you're not an administrator, you can download Qt here instead). Also see this answer.

Joining two lists together

See this link

public class ProductA
{ 
public string Name { get; set; }
public int Code { get; set; }
}

public class ProductComparer : IEqualityComparer<ProductA>
{

public bool Equals(ProductA x, ProductA y)
{
    //Check whether the objects are the same object. 
    if (Object.ReferenceEquals(x, y)) return true;

    //Check whether the products' properties are equal. 
    return x != null && y != null && x.Code.Equals(y.Code) && x.Name.Equals(y.Name);
    }

public int GetHashCode(ProductA obj)
{
    //Get hash code for the Name field if it is not null. 
    int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();

    //Get hash code for the Code field. 
    int hashProductCode = obj.Code.GetHashCode();

    //Calculate the hash code for the product. 
    return hashProductName ^ hashProductCode;
}
}


    ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 }, 
                   new ProductA { Name = "orange", Code = 4 } };

    ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 }, 
                   new ProductA { Name = "lemon", Code = 12 } };

//Get the products from the both arrays //excluding duplicates.

IEnumerable<ProductA> union =
  store1.Union(store2);

foreach (var product in union)
    Console.WriteLine(product.Name + " " + product.Code);

/*
    This code produces the following output:

    apple 9
    orange 4
    lemon 12
*/

Json.net serialize/deserialize derived types?

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

How to initialize List<String> object in Java?

You will need to use ArrayList<String> or such.

List<String> is an interface.

Use this:

import java.util.ArrayList;

...

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

How do I create a self-signed certificate for code signing on Windows?

As of PowerShell 4.0 (Windows 8.1/Server 2012 R2) it is possible to make a certificate in Windows without makecert.exe.

The commands you need are New-SelfSignedCertificate and Export-PfxCertificate.

Instructions are in Creating Self Signed Certificates with PowerShell.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Extract digits from a string in Java

public class FindDigitFromString 
{

    public static void main(String[] args) 
    {
        String s="  Hi How Are You 11  ";        
        String s1=s.replaceAll("[^0-9]+", "");
        //*replacing all the value of string except digit by using "[^0-9]+" regex.*
       System.out.println(s1);          
   }
}

Output: 11

Kill detached screen session

You can just go to the place where the screen session is housed and run:

 screen -ls

which results in

 There is a screen on:
         26727.pts-0.devxxx      (Attached)
 1 Socket in /tmp/uscreens/S-xxx. <------ this is where the session is.

And just remove it:

  1. cd /tmp/uscreens/S-xxx
  2. ls
  3. 26727.pts-0.devxxx
  4. rm 26727.pts-0.devxxx
  5. ls

The uscreens directory will not have the 26727.pts-0.devxxx file in it anymore. Now to make sure just type this:

screen -ls

and you should get:

No Sockets found in /tmp/uscreens/S-xxx.

How to get the body's content of an iframe in Javascript?

use content in iframe with JS:

document.getElementById('id_iframe').contentWindow.document.write('content');

How can I recover a lost commit in Git?

Another way to get to the deleted commit is with the git fsck command.

git fsck --lost-found

This will output something like at the last line:

dangling commit xyz

We can check that it is the same commit using reflog as suggested in other answers. Now we can do a git merge

git merge xyz

Note:
We cannot get the commit back with fsck if we have already run a git gc command which will remove the reference to the dangling commit.

What are naming conventions for MongoDB?

I think it's all personal preference. My preferences come from using NHibernate, in .NET, with SQL Server, so they probably differ from what others use.

  • Databases: The application that's being used.. ex: Stackoverflow
  • Collections: Singular in name, what it's going to be a collection of, ex: Question
  • Document fields, ex: MemberFirstName

Honestly, it doesn't matter too much, as long as it's consistent for the project. Just get to work and don't sweat the details :P

Don't reload application when orientation changes

Prevent Activity to recreated Most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest.xml. Using this attribute your Activities won’t be recreated and all your views and data will still be there after orientation change.

<activity
    android:name="com.example.test.activity.MainActivity"
    android:configChanges="orientation|screenSize|keyboardHidden"/>

this is work for me

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

How do I get the title of the current active window using c#?

If you were talking about WPF then use:

 Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);

How to make the overflow CSS property work with hidden as value

In addition to provided answers:

it seems like parent element (the one with overflow:hidden) must not be display:inline. Changing to display:inline-block worked for me.

_x000D_
_x000D_
.outer {_x000D_
  position: relative;_x000D_
  border: 1px dotted black;_x000D_
  padding: 5px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.inner {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  margin-left: -20px;_x000D_
  top: 70%;_x000D_
  width: 40px;_x000D_
  height: 80px;_x000D_
  background: yellow;_x000D_
}
_x000D_
<span class="outer">_x000D_
  Some text_x000D_
  <span class="inner"></span>_x000D_
</span>_x000D_
<span class="outer" style="display:inline-block;">_x000D_
  Some text_x000D_
  <span class="inner"></span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

What evaluates to True/False in R?

This is documented on ?logical. The pertinent section of which is:

Details:

     ‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
     in the R language, whereas ‘T’ and ‘F’ are global variables whose
     initial values set to these.  All four are ‘logical(1)’ vectors.

     Logical vectors are coerced to integer vectors in contexts where a
     numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
     ‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.

The second paragraph there explains the behaviour you are seeing, namely 5 == 1L and 5 == 0L respectively, which should both return FALSE, where as 1 == 1L and 0 == 0L should be TRUE for 1 == TRUE and 0 == FALSE respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE and FALSE in R, i.e. what numeric values they take when coerced to numeric.

However, only TRUE is guaranteed to the be TRUE:

> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE

isTRUE is a wrapper for identical(x, TRUE), and from ?isTRUE we note:

Details:
....

     ‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
     true if and only if ‘x’ is a length-one logical vector whose only
     element is ‘TRUE’ and which has no attributes (not even names).

So by the same virtue, only FALSE is guaranteed to be exactly equal to FALSE.

> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE

If this concerns you, always use isTRUE() or identical(x, FALSE) to check for equivalence with TRUE and FALSE respectively. == is not doing what you think it is.

How can I initialize a String array with length 0 in Java?

As others have said,

new String[0]

will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:

private static final String[] EMPTY_ARRAY = new String[0];

and then just return EMPTY_ARRAY each time you need it - there's no need to create a new object each time.

WAMP Server doesn't load localhost

Change the port 80 to port 8080 and restart all services and access like localhost:8080/

It will work fine.

How to open URL in Microsoft Edge from the command line?

It will do more or less the same thing in good old dos script fashion

set add=%1
if %add%$ ==$ set add="about:blank" && goto launch

rem http://
set test=%add:~0, 7%
if %test% == http:// goto launch

rem ftp:// 
set test=%add:~0, 6%
if %test% == ftp:// goto launch

rem https://
set test=%add:~0, 8%
if %test% == https:// goto launch

rem add http
set add=http://%add%

:launch
start microsoft-edge:%add%

How to sort a HashSet?

Based on the answer given by @LazerBanana i will put my own example of a Set sorted by the Id of the Object:

Set<Clazz> yourSet = [...];

yourSet.stream().sorted(new Comparator<Clazz>() {
    @Override
    public int compare(Clazz o1, Clazz o2) {
        return o1.getId().compareTo(o2.getId());
    }
}).collect(Collectors.toList()); // Returns the sorted List (using toSet() wont work)

How to hide scrollbar in Firefox?

I was able to hide the scrollbar but still be able to scroll with mouse wheel with this solution:

html {overflow: -moz-scrollbars-none;}

Download the plugin https://github.com/brandonaaron/jquery-mousewheel and include this function:

jQuery('html,body').bind('mousewheel', function(event) {
    event.preventDefault();
    var scrollTop = this.scrollTop;
    this.scrollTop = (scrollTop + ((event.deltaY * event.deltaFactor) * -1));
    //console.log(event.deltaY, event.deltaFactor, event.originalEvent.deltaMode, event.originalEvent.wheelDelta);
  });

Set TextView text from html-formatted string resource in XML

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old:

When using String resources in Android, you just have to call getString(...) from Java code or use android:text="@string/..." in your layout XML.

Even if you want to use HTML markup in your Strings, you don't have to change a lot:

The only characters that you need to escape in your String resources are:

  • double quotation mark: " becomes \"
  • single quotation mark: ' becomes \'
  • ampersand: & becomes &#38; or &amp;

That means you can add your HTML markup without escaping the tags:

<string name="my_string"><b>Hello World!</b> This is an example.</string>

However, to be sure, you should only use <b>, <i> and <u> as they are listed in the documentation.

If you want to use your HTML strings from XML, just keep on using android:text="@string/...", it will work fine.

The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(...) instead of getString(...) now, as the former keeps the style and the latter will just strip it off.

It's as easy as that. No CDATA, no Html.fromHtml(...).

You will only need Html.fromHtml(...) if you did encode your special characters in HTML markup. Use it with getString(...) then. This can be necessary if you want to pass the String to String.format(...).

This is all described in the docs as well.

Edit:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...).

See the following graphic for a comparison:

enter image description here

jQuery - Check if DOM element already exists

(()=> {
    var elem = document.querySelector('.elem');  
    (
        (elem) ? 
        console.log(elem+' was found.') :
        console.log('not found')
    )
})();

If it exists, it spits out the specified element as a DOM object. With JQuery $('.elem') it only tells you that it's an object if found but not which.

Array versus linked-list

Arrays make sense where the exact number of items will be known, and where searching by index makes sense. For example, if I wanted to store the exact state of my video output at a given moment without compression I would probably use an array of size [1024][768]. This will provide me with exactly what I need, and a list would be much, much slower to get the value of a given pixel. In places where an array does not make sense there are generally better data types than a list to deal with data effectively.

How to map calculated properties with JPA and Hibernate

You have three options:

  • either you are calculating the attribute using a @Transient method
  • you can also use @PostLoad entity listener
  • or you can use the Hibernate specific @Formula annotation

While Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:

@Column(name = "price")
private Double price;

@Column(name = "tax_percentage")
private Double taxes;

@Transient
private Double priceWithTaxes;

@PostLoad
private void onLoad() {
    this.priceWithTaxes = price * taxes;
}

So, you can use the Hibernate @Formula like this:

@Formula("""
    round(
       (interestRate::numeric / 100) *
       cents *
       date_part('month', age(now(), createdOn)
    )
    / 12)
    / 100::numeric
    """)
private double interestDollars;

Validating parameters to a Bash script

I would use bash's [[:

if [[ ! ("$#" == 1 && $1 =~ ^[0-9]+$ && -d $1) ]]; then 
    echo 'Please pass a number that corresponds to a directory'
    exit 1
fi

I found this faq to be a good source of information.

C99 stdint.h header and MS Visual Studio

Just define them yourself.

#ifdef _MSC_VER

typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;

#else
#include <stdint.h>
#endif

What are the differences between the different saving methods in Hibernate?

None of the following answers are right. All these methods just seem to be alike, but in practice do absolutely different things. It is hard to give short comments. Better to give a link to full documentation about these methods: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html

How do I do multiple CASE WHEN conditions using SQL Server 2008?

This can be an efficient way of performing different tests on a single statement

select
case colour_txt 
  when 'red' then 5 
  when 'green' then 4 
  when 'orange' then 3
else 0 
end as Pass_Flag

this only works on equality comparisons!