Programs & Examples On #Inner query

Converting a PDF to PNG

Try to extract a single page.

$page = 4

gs -sDEVICE=pngalpha -dFirstPage="$page" -dLastPage="$page" -o thumb.png -r144 input.pdf

SQL: Return "true" if list of records exists?

Assuming you're using SQL Server, the boolean type doesn't exist, but the bit type does, which can hold only 0 or 1 where 0 represents False, and 1 represents True.

I would go this way:

select 1
    from Products
    where ProductId IN (1, 10, 100)

Here, a null or no row will be returned (if no row exists).

Or even:

select case when EXISTS (
    select 1
        from Products
        where ProductId IN (1, 10, 100)
    ) then 1 else 0 end as [ProductExists]

Here, either of the scalar values 1 or 0 will always be returned (if no row exists).

Centering a button vertically in table cell, using Twitter Bootstrap

To fix this, i put this class on the webpage

<style>                        
    td.vcenter {
        vertical-align: middle !important;
        text-align: center !important;
    }
</style>

and this in my TemplateField

<asp:TemplateField ItemStyle-CssClass="vcenter">

as the CSS class points directly to the td (tabledata) element and has the !important statment at the end each setting. It will over rule bootsraps CSS class settings.

Hope it helps

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

The @android did not work for me. When I use android (without the @) it works like a charm.

Example:

<style name="CustomActionBarTheme"
       parent="android:style/Theme.Holo.Light.DarkActionBar">

Print execution time of a shell command

Don't forget that there is a difference between bash's builtin time (which should be called by default when you do time command) and /usr/bin/time (which should require you to call it by its full path).

The builtin time always prints to stderr, but /usr/bin/time will allow you to send time's output to a specific file, so you do not interfere with the executed command's stderr stream. Also, /usr/bin/time's format is configurable on the command line or by the environment variable TIME, whereas bash's builtin time format is only configured by the TIMEFORMAT environment variable.

$ time factor 1234567889234567891 # builtin
1234567889234567891: 142662263 8653780357

real    0m3.194s
user    0m1.596s
sys 0m0.004s
$ /usr/bin/time factor 1234567889234567891
1234567889234567891: 142662263 8653780357
1.54user 0.00system 0:02.69elapsed 57%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+215minor)pagefaults 0swaps
$ /usr/bin/time -o timed factor 1234567889234567891 # log to file `timed`
1234567889234567891: 142662263 8653780357
$ cat timed
1.56user 0.02system 0:02.49elapsed 63%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+217minor)pagefaults 0swaps

Set up DNS based URL forwarding in Amazon Route53

I was able to use nginx to handle the 301 redirect to the aws signin page.

Go to your nginx conf folder (in my case it's /etc/nginx/sites-available in which I create a symlink to /etc/nginx/sites-enabled for the enabled conf files).

Then add a redirect path

server {
  listen 80;
  server_name aws.example.com;
  return 301 https://myaccount.signin.aws.amazon.com/console;
}

If you are using nginx, you will most likely have additional server blocks (virtualhosts in apache terminology) to handle your zone apex (example.com) or however you have it setup. Make sure that you have one of them set to be your default server.

server {
  listen 80 default_server;
  server_name example.com;
  # rest of config ...
}

In Route 53, add an A record for aws.example.com and set the value to the same IP used for your zone apex.

Is there a difference between "throw" and "throw ex"?

Throw preserves the stack trace. So lets say Source1 throws Error1 , its caught by Source2 and Source2 says throw then Source1 Error + Source2 Error will be available in the stack trace.

Throw ex does not preserve the stack trace. So all errors of Source1 will be wiped out and only Source2 error will sent to the client.

Sometimes just reading things are not clear , would suggest to watch this video demo to get more clarity , Throw vs Throw ex in C#.

Throw vs Throw ex

Retrieve the position (X,Y) of an HTML element relative to the browser window

If you want it done only in javascript, here are some one liners using getBoundingClientRect()

window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y

window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X

The first line will return offsetTop say Y relative to document. The second line will return offsetLeft say X relative to document.

getBoundingClientRect() is a javascript function that returns the position of the element relative to viewport of window.

How to perform element-wise multiplication of two lists?

gahooa's answer is correct for the question as phrased in the heading, but if the lists are already numpy format or larger than ten it will be MUCH faster (3 orders of magnitude) as well as more readable, to do simple numpy multiplication as suggested by NPE. I get these timings:

0.0049ms -> N = 4, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0075ms -> N = 4, a = [i for i in range(N)], c = a * b
0.0167ms -> N = 4, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0013ms -> N = 4, a = np.arange(N), c = a * b
0.0171ms -> N = 40, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0095ms -> N = 40, a = [i for i in range(N)], c = a * b
0.1077ms -> N = 40, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0013ms -> N = 40, a = np.arange(N), c = a * b
0.1485ms -> N = 400, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0397ms -> N = 400, a = [i for i in range(N)], c = a * b
1.0348ms -> N = 400, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0020ms -> N = 400, a = np.arange(N), c = a * b

i.e. from the following test program.

import timeit

init = ['''
import numpy as np
N = {}
a = {}
b = np.linspace(0.0, 0.5, len(a))
'''.format(i, j) for i in [4, 40, 400] 
                  for j in ['[i for i in range(N)]', 'np.arange(N)']]

func = ['''c = [a*b for a,b in zip(a, b)]''',
'''c = a * b''']

for i in init:
  for f in func:
    lines = i.split('\n')
    print('{:6.4f}ms -> {}, {}, {}'.format(
           timeit.timeit(f, setup=i, number=1000), lines[2], lines[3], f))

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

You were close:

IF EXISTS (SELECT * FROM Table WHERE FieldValue='')
   SELECT TableID FROM Table WHERE FieldValue=''
ELSE
BEGIN
   INSERT INTO TABLE (FieldValue) VALUES ('')
   SELECT TableID FROM Table WHERE TableID=SCOPE_IDENTITY()
END

How do I get the path and name of the file that is currently executing?

I think this is cleaner:

import inspect
print inspect.stack()[0][1]

and gets the same information as:

print inspect.getfile(inspect.currentframe())

Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.

print inspect.stack()[1][1]

would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script.

Run class in Jar file

This is the right way to execute a .jar, and whatever one class in that .jar should have main() and the following are the parameters to it :

java -DLB="uk" -DType="CLIENT_IND" -jar com.fbi.rrm.rrm-batchy-1.5.jar

CSS to set A4 paper size

I looked into this a bit more and the actual problem seems to be with assigning initial to page width under the print media rule. It seems like in Chrome width: initial on the .page element results in scaling of the page content if no specific length value is defined for width on any of the parent elements (width: initial in this case resolves to width: auto ... but actually any value smaller than the size defined under the @page rule causes the same issue).

So not only the content is now too long for the page (by about 2cm), but also the page padding will be slightly more than the initial 2cm and so on (it seems to render the contents under width: auto to the width of ~196mm and then scale the whole content up to the width of 210mm ~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm).

To fix this problem you can simply in the print media rule assign the A4 paper width and hight to html, body or directly to .page and in this case avoid the initial keyword.

DEMO

@page {
  size: A4;
  margin: 0;
}
@media print {
  html, body {
    width: 210mm;
    height: 297mm;
  }
  /* ... the rest of the rules ... */
}

This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).

Confused about __str__ on list in Python

Answer to the question

As pointed out in another answer and as you can read in PEP 3140, str on a list calls for each item __repr__. There is not much you can do about that part.

If you implement __repr__, you will get something more descriptive, but if implemented correctly, not exactly what you expected.

Proper implementation

The fast, but wrong solution is to alias __repr__ to __str__.

__repr__ should not be set to __str__ unconditionally. __repr__ should create a representation, that should look like a valid Python expression that could be used to recreate an object with the same value. In this case, this would rather be Node(2) than 2.

A proper implementation of __repr__ makes it possible to recreate the object. In this example, it should also contain the other significant members, like neighours and distance.

An incomplete example:

class Node:

    def __init__(self, id, neighbours=[], distance=0):
        self.id = id
        self.neighbours = neighbours
        self.distance = distance


    def __str__(self):
        return str(self.id)


    def __repr__(self):
        return "Node(id={0.id}, neighbours={0.neighbours!r}, distance={0.distance})".format(self)
        # in an elaborate implementation, members that have the default
        # value could be left out, but this would hide some information


uno = Node(1)    
due = Node(2)    
tri = Node(3)    
qua = Node(4)

print uno
print str(uno)
print repr(uno)

uno.neighbours.append([[due, 4], [tri, 5]])

print uno
print uno.neighbours
print repr(uno)

Note: print repr(uno) together with a proper implementation of __eq__ and __ne__ or __cmp__ would allow to recreate the object and check for equality.

Show spinner GIF during an $http request in AngularJS?

Another solution to show loading between different url changes is:

$rootScope.$on('$locationChangeStart', function() {
  $scope.loading++;
});

$rootScope.$on('$locationChangeSuccess', function() {
  $timeout(function() {
    $scope.loading--;
  }, 300);
});

And then in the markup just toggle the spinner with ng-show="loading".

If you want to display it on ajax requests just add $scope.loading++ when the request starts and when it ends add $scope.loading--.

What does "#pragma comment" mean?

#pragma comment is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files.

#pragma comment(lib, libname) tells the linker to add the 'libname' library to the list of library dependencies, as if you had added it in the project properties at Linker->Input->Additional dependencies

See #pragma comment on MSDN

Switch php versions on commandline ubuntu 16.04

From PHP 5.6 => PHP 7.1

$ sudo a2dismod php5.6
$ sudo a2enmod php7.1

for old linux versions

 $ sudo service apache2 restart

for more recent version

$ systemctl restart apache2

How do I center an anchor element in CSS?

Two options, that have different uses:

HTML:

<a class="example" href="http://www.example.com">example</a>

CSS:

.example { text-align: center; }

Or:

.example { display:block; width:100px; margin:0 auto;}

Custom checkbox image android

If you are using custom adapters than android:focusable="false" and android:focusableInTouchMode="false" are nessesury to make list items clickable while using checkbox.

<CheckBox
        android:id="@+id/checkbox_fav"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/checkbox_layout"/>

In drawable>checkbox_layout.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/uncked_checkbox"
        android:state_checked="false"/>
    <item android:drawable="@drawable/selected_checkbox"
        android:state_checked="true"/>
    <item android:drawable="@drawable/uncked_checkbox"/>
</selector>

Displaying files (e.g. images) stored in Google Drive on a website

If you want to view the file in the browser, it's also possible using a similar method to the one provided by rufo and Torxed:

https://drive.google.com/uc?export=view&id={fileId}

How can I convert a DOM element to a jQuery element?

So far best solution that I've made:

function convertHtmlToJQueryObject(html){
    var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
    return $(htmlDOMObject.documentElement);
}

How to place div side by side

Give the first div float: left; and a fixed width, and give the second div width: 100%; and float: left;. That should do the trick. If you want to place items below it you need a clear: both; on the item you want to place below it.

Stop fixed position at footer

If your elements are glitching this is probably because when you change the position to relative the Y position of the footer increases which tries to send the item back to fixed which creates a loop. You can avoid this by setting two different cases when scrolling up and down. You don't even need to reference the fixed element, just the footer, and window size.

const footer = document.querySelector('footer');
document.addEventListener("scroll", checkScroll);

let prevY = window.scrollY + window.innerHeight;
function checkScroll() {
  let footerTop = getRectTop(footer) + window.scrollY;
  let windowBottomY = window.scrollY + window.innerHeight;
  if (prevY < windowBottomY) {  // Scroll Down
    if (windowBottomY > footerTop)
      setScrolledToFooter(true) // using React state. Change class or change style in JS.
  } else { // Scroll Up
    if (windowBottomY <= footerTop)
      setScrolledToFooter(false)
  }
  prevY = windowBottomY
};

function getRectTop(el) {
  var rect = el.getBoundingClientRect();
  return rect.top;
}

and the position of the element in the style object as follows:

position: scrolledToFooter ? 'relative' : 'fixed'

Where can I download an offline installer of Cygwin?

I'm not a big fan of Cygwin. It is good if you have some Unix code that requires a full POSIX system, I suppose. Even then, using it renders your programs GPL (due to the GPLed DLL), unless you pay Red Hat for a different license.

Most people should be using MinGW (and MSYS) instead. This gives you the Unix shell and utilities (even compilers, if you want them) without the purposely infectious DLL. Most of the folks using GNU compilers on Windows are using MinGW (although some don't realise it).

Just as importantly for your purposes, you can download the parts separately, rather than use the re-downloading installer.

The SourceForge download page is here. I'd suggest starting with the MSYS Base System package, which will give you the coreutils, Bash, make, tar, etc. If there's other stuff you need, you can pick and choose from the list of packages.

WCF service startup error "This collection already contains an address with scheme http"

I came by the same error on an old 2010 Exchange Server. A service(Exchange mailbox replication service) was giving out the above error and the migration process could not be continued. Searching through the internet, i came by this link which stated the below:

The Exchange GRE fails to open when installed for the first time or if any changes are made to the IIS server. It fails with snap-in error and when you try to open the snap-in page, the following content is displayed:

This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection. If your service is being hosted in IIS you can fix the problem by setting 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' to true or specifying 'system.serviceModel/serviceHostingEnvironment/baseAddressPrefixFilters'."

Cause: This error occurs because http port number 443 is already in use by another application and the IIS server is not configured to handle multiple binding to the same port.

Solution: Configure IIS server to handle multiple port bindings. Contact the vendor (Microsoft) to configure it.

Since these services were offered from an IIS Web Server, checking the Bindings on the Root Site fixed the problem. Someone had messed up the Site Bindings, defining rules that were overlapping themselves and messed up the services.

Fixing the correct Bindings resolved the problem, in my case, and i did not have to configure the Web.Config.

Android disable screen timeout while app is running

Put this at onStart

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "no sleep");
    wakeLock.acquire();

And this at you manifest

    <uses-permission android:name="android.permission.WAKE_LOCK" />

Don't forget to

wakeLock.release();

at onStop

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

How can I commit a single file using SVN over a network?

You can use

cd /You folder name
svn commit 'your file path' -m "Commit message you want to give"

You can also drage you files to command promt instead to write cd [common in MAC OSx]

How to split page into 4 equal parts?

I did not want to add style to <body> tag and <html> tag.

_x000D_
_x000D_
.quodrant{
    width: 100%;
    height: 100vh;
    margin: 0;
    padding: 0;
}

.qtop,
.qbottom{
    width: 100%;
    height: 50vh;
}

.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
    display: inline;
    float: left;
    width: 50%;
    height: 100%;
}

.quodrant1{
    top: 0;
    left: 50vh;
    background-color: red;
}

.quodrant2{
    top: 0;
    left: 0;
    background-color: yellow;
}

.quodrant3{
    top: 50vw;
    left: 0;
    background-color: blue;
}

.quodrant4{ 
    top: 50vw;
    left: 50vh;
    background-color: green;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>

<div class='quodrant'>
    <div class='qtop'>
        <div class='quodrant1'></div>
        <div class='quodrant2'></div>
    </div>
    <div class='qbottom'>
        <div class='quodrant3'></div>
        <div class='quodrant4'></div>
    </div>
</div>

<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

Or making it looks nicer.

_x000D_
_x000D_
.quodrant{
    width: 100%;
    height: 100vh;
    margin: 0;
    padding: 0;
}

.qtop,
.qbottom{
    width: 96%;
    height: 46vh;
}

.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
    display: inline;
    float: left;
    width: 46%;
    height: 96%;
    border-radius: 30px;
    margin: 2%;
}

.quodrant1{
    background-color: #948be5;
}

.quodrant2{
    background-color: #22e235;
}

.quodrant3{
    background-color: #086e75;
}

.quodrant4{ 
    background-color: #7cf5f9;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>

<div class='quodrant'>
    <div class='qtop'>
        <div class='quodrant1'></div>
        <div class='quodrant2'></div>
    </div>
    <div class='qbottom'>
        <div class='quodrant3'></div>
        <div class='quodrant4'></div>
    </div>
</div>

<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

How to take MySQL database backup using MySQL Workbench?

Sever > Data Export

enter image description here

Select database, and start export

enter image description here

Press enter in textbox to and execute button command

If buttonSearch has no code, and only action is to return dialog result then:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            DialogResult = DialogResult.OK;
    }

How to get all options of a select using jQuery?

The short way

$(() => {
$('#myselect option').each((index, data) => {
    console.log(data.attributes.value.value)
})})

or

export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
    arry.push(mData.children[index].value);
}
return arry;}

Get the previous month's first and last day dates in c#

DateTime LastMonthLastDate = DateTime.Today.AddDays(0 - DateTime.Today.Day);
DateTime LastMonthFirstDate = LastMonthLastDate.AddDays(1 - LastMonthLastDate.Day);

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Using ensure_ascii=False in json.dumps is the right direction to solve this problem, as pointed out by Martijn. However, this may raise an exception:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 1: ordinal not in range(128)

You need extra settings in either site.py or sitecustomize.py to set your sys.getdefaultencoding() correct. site.py is under lib/python2.7/ and sitecustomize.py is under lib/python2.7/site-packages.

If you want to use site.py, under def setencoding(): change the first if 0: to if 1: so that python will use your operation system's locale.

If you prefer to use sitecustomize.py, which may not exist if you haven't created it. simply put these lines:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

Then you can do some Chinese json output in utf-8 format, such as:

name = {"last_name": u"?"}
json.dumps(name, ensure_ascii=False)

You will get an utf-8 encoded string, rather than \u escaped json string.

To verify your default encoding:

print sys.getdefaultencoding()

You should get "utf-8" or "UTF-8" to verify your site.py or sitecustomize.py settings.

Please note that you could not do sys.setdefaultencoding("utf-8") at interactive python console.

adb server version doesn't match this client

I also had this problem today, turns out I disabled my network drivers because I had WIFI/LAN issues. re-enabling fixed the issue

logout and redirecting session in php

The simplest way to log out and redirect back to the login or index:

<?php
    if (!isset($_SESSION)) { session_start(); }
    $_SESSION = array(); 
    session_destroy(); 
    header("Location: login.php"); // Or wherever you want to redirect
    exit();
?>

Print line numbers starting at zero using awk

Another option besides awk is nl which allows for options -v for setting starting value and -n <lf,rf,rz> for left, right and right with leading zeros justified. You can also include -s for a field separator such as -s "," for comma separation between line numbers and your data.

In a Unix environment, this can be done as

cat <infile> | ...other stuff... | nl -v 0 -n rz

or simply

nl -v 0 -n rz <infile>

Example:

echo "Here 
are
some 
words" > words.txt

cat words.txt | nl -v 0 -n rz

Out:

000000      Here
000001      are
000002      some
000003      words

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

For Windows, you can check the official Intel MKL optimization for TensorFlow wheels that are compiled with AVX2. This solution speeds up my inference ~x3.

conda install tensorflow-mkl

Replace non-ASCII characters with a single space

For you the get the most alike representation of your original string I recommend the unidecode module:

from unidecode import unidecode
def remove_non_ascii(text):
    return unidecode(unicode(text, encoding = "utf-8"))

Then you can use it in a string:

remove_non_ascii("Ceñía")
Cenia

Use async await with Array.map

The problem here is that you are trying to await an array of promises rather than a promise. This doesn't do what you expect.

When the object passed to await is not a Promise, await simply returns the value as-is immediately instead of trying to resolve it. So since you passed await an array (of Promise objects) here instead of a Promise, the value returned by await is simply that array, which is of type Promise<number>[].

What you need to do here is call Promise.all on the array returned by map in order to convert it to a single Promise before awaiting it.

According to the MDN docs for Promise.all:

The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects.

So in your case:

var arr = [1, 2, 3, 4, 5];

var results: number[] = await Promise.all(arr.map(async (item): Promise<number> => {
    await callAsynchronousOperation(item);
    return item + 1;
}));

This will resolve the specific error you are encountering here.

Why is PHP session_destroy() not working?

Well, this seems a new problem for me, using a new php server. In the past never had an issue with sessions not ending.

In a test of sessions, I setup a session, ran a session count++ and closed the session. Reloaded the page and to my surprise the variable remained.

I tried the following suggestion posted by mc10

session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable

However, that did not work. I did not think it could work as the session was not active after destroying it, so I reversed it.

$_SESSION = array();
session_destroy();

That worked, reloading the page starting sessios and reviewing the set variables all showed them empty/not-set.

Really not sure why session_destroy() does not work on this PHP Version 5.3.14 server.

Don't really care as long as I know how to clear the sessions.

MongoDB query multiple collections at once

As mentioned before in MongoDB you can't JOIN between collections.

For your example a solution could be:

var myCursor = db.users.find({admin:1});
var user_id = myCursor.hasNext() ? myCursor.next() : null;
db.posts.find({owner_id : user_id._id});

See the reference manual - cursors section: http://es.docs.mongodb.org/manual/core/cursors/

Other solution would be to embed users in posts collection, but I think for most web applications users collection need to be independent for security reasons. Users collection might have Roles, permissons, etc.

posts
{
 "content":"Some content",
 "user":{"_id":"12345", "admin":1},
 "via":"facebook"
},
{
 "content":"Some other content",
 "user":{"_id":"123456789", "admin":0},
 "via":"facebook"
}

and then:

db.posts.find({user.admin: 1 });

Generate an HTML Response in a Java Servlet

You need to have a doGet method as:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("</body>");
    out.println("</html>");
}

You can see this link for a simple hello world servlet

insert a NOT NULL column to an existing table

Other SQL implementations have similar restrictions. The reason is that adding a column requires adding values for that column (logically, even if not physically), which default to NULL. If you don't allow NULL, and don't have a default, what is the value going to be?

Since SQL Server supports ADD CONSTRAINT, I'd recommend Pavel's approach of creating a nullable column, and then adding a NOT NULL constraint after you've filled it with non-NULL values.

How can I see the request headers made by curl when sending a request to the server?

curl -s -v -o/dev/null -H "Testheader: test" http://www.example.com

You could also use -I option if you want to send a HEAD request and not a GET request.

Disabling Strict Standards in PHP 5.4

As the commenters have stated the best option is to fix the errors, but with limited time or knowledge, that's not always possible. In your php.ini change

error_reporting = E_ALL

to

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT

If you don't have access to the php.ini, you can potentially put this in your .htaccess file:

php_value error_reporting 30711

This is the E_ALL value (32767) and the removing the E_STRICT (2048) and E_NOTICE (8) values.

If you don't have access to the .htaccess file or it's not enabled, you'll probably need to put this at the top of the PHP section of any script that gets loaded from a browser call:

error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);

One of those should help you be able to use the software. The notices and strict stuff are indicators of problems or potential problems though and you may find some of the code is not working correctly in PHP 5.4.

jquery's append not working with svg element?

The increasingly popular D3 library handles the oddities of appending/manipulating svg very nicely. You may want to consider using it as opposed to the jQuery hacks mentioned here.

HTML

<svg xmlns="http://www.w3.org/2000/svg"></svg>

Javascript

var circle = d3.select("svg").append("circle")
    .attr("r", "10")
    .attr("style", "fill:white;stroke:black;stroke-width:5");

BATCH file asks for file or folder

The trick of appending "*" can be made to work when the new extension is shorter. You need to pad the new extension with blanks, which can only be done by enclosing the destination file name in quotes. For example:

xcopy foo.shtml "foo.html *"

This will copy and rename without prompting.

"That's not a bug, it's a feature!" (I once saw a VW Beetle in the Microsoft parking lot with the vanity plate "FEATURE".) These semantics for rename go all the way back to when I wrote DOS v.1. Characters in the new name are substituted one by one for characters in the old name, unless a wildcard character (? or *) is present in the new name. Without adding the blank(s) to the new name, remaining characters are copied from the old name.

Why do we use Base64?

In addition to the other (somewhat lengthy) answers: even ignoring old systems that support only 7-bit ASCII, basic problems with supplying binary data in text-mode are:

  • Newlines are typically transformed in text-mode.
  • One must be careful not to treat a NUL byte as the end of a text string, which is all too easy to do in any program with C lineage.

How to restart a single container with docker-compose

The other answers to restarting a single node are on target, docker-compose restart worker. That will bounce that container, but not include any changes, even if you rebuilt it separately. You can manually stop, rm, create, and start, but there are much easier methods.

If you've updated your code, you can do the build and reload in a single step with:

docker-compose up --detach --build

That will first rebuild your images from any changed code, which is fast if there are no changes since the cache is reused. And then it only replaces the changed containers. If your downloaded images are stale, you can precede the above command with:

docker-compose pull

To download any changed images first (the containers won't be restarted until you run a command like the up above). Doing an initial stop is unnecessary.

And to only do this for a single service, follow the up or pull command with the services you want to specify, e.g.:

docker-compose up --detach --build worker

Here's a quick example of the first option, the Dockerfile is structured to keep the frequently changing parts of the code near the end. In fact the requirements are pulled in separately for the pip install since that file rarely changes. And since the nginx and redis containers were up-to-date, they weren't restarted. Total time for the entire process was under 6 seconds:

$ time docker-compose -f docker-compose.nginx-proxy.yml up --detach --build
Building counter
Step 1 : FROM python:2.7-alpine
 ---> fc479af56697
Step 2 : WORKDIR /app
 ---> Using cache
 ---> d04d0d6d98f1
Step 3 : ADD requirements.txt /app/requirements.txt
 ---> Using cache
 ---> 9c4e311f3f0c
Step 4 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> 85b878795479
Step 5 : ADD . /app
 ---> 63e3d4e6b539
Removing intermediate container 9af53c35d8fe
Step 6 : EXPOSE 80
 ---> Running in a5b3d3f80cd4
 ---> 4ce3750610a9
Removing intermediate container a5b3d3f80cd4
Step 7 : CMD gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0
 ---> Running in 0d69957bda4c
 ---> d41ff1635cb7
Removing intermediate container 0d69957bda4c
Successfully built d41ff1635cb7
counter_nginx_1 is up-to-date
counter_redis_1 is up-to-date
Recreating counter_counter_1

real    0m5.959s
user    0m0.508s
sys     0m0.076s

How to get IntPtr from byte[] in C#

This should work but must be used within an unsafe context:

byte[] buffer = new byte[255];
fixed (byte* p = buffer)
{
    IntPtr ptr = (IntPtr)p;
    // do you stuff here
}

beware, you have to use the pointer in the fixed block! The gc can move the object once you are not anymore in the fixed block.

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

If you don't wish to compile bootstrap, copy the following and insert it in your custom css file. It's not recommended to change the original bootstrap css file. Also, you won't be able to modify the bootstrap original css if you are loading it from a cdn.

Paste this in your custom css file:

@media (min-width:992px)
    {
        .container{width:960px}
    }
@media (min-width:1200px)
    {
        .container{width:960px}
    }

I am here setting my container to 960px for anything that can accommodate it, and keeping the rest media sizes to default values. You can set it to 940px for this problem.

Entity Framework: table without primary key

THIS SOLUTION WORKS

You do not need to map manually even if you dont have a PK. You just need to tell the EF that one of your columns is index and index column is not nullable.

To do this you can add a row number to your view with isNull function like the following

select 
    ISNULL(ROW_NUMBER() OVER (ORDER BY xxx), - 9999) AS id
from a

ISNULL(id, number) is the key point here because it tells the EF that this column can be primary key

What does AND 0xFF do?

The byte1 & 0xff ensures that only the 8 least significant bits of byte1 can be non-zero.

if byte1 is already an unsigned type that has only 8 bits (e.g., char in some cases, or unsigned char in most) it won't make any difference/is completely unnecessary.

If byte1 is a type that's signed or has more than 8 bits (e.g., short, int, long), and any of the bits except the 8 least significant is set, then there will be a difference (i.e., it'll zero those upper bits before oring with the other variable, so this operand of the or affects only the 8 least significant bits of the result).

Detect If Browser Tab Has Focus

I would do it this way (Reference http://www.w3.org/TR/page-visibility/):

    window.onload = function() {

        // check the visiblility of the page
        var hidden, visibilityState, visibilityChange;

        if (typeof document.hidden !== "undefined") {
            hidden = "hidden", visibilityChange = "visibilitychange", visibilityState = "visibilityState";
        }
        else if (typeof document.mozHidden !== "undefined") {
            hidden = "mozHidden", visibilityChange = "mozvisibilitychange", visibilityState = "mozVisibilityState";
        }
        else if (typeof document.msHidden !== "undefined") {
            hidden = "msHidden", visibilityChange = "msvisibilitychange", visibilityState = "msVisibilityState";
        }
        else if (typeof document.webkitHidden !== "undefined") {
            hidden = "webkitHidden", visibilityChange = "webkitvisibilitychange", visibilityState = "webkitVisibilityState";
        }


        if (typeof document.addEventListener === "undefined" || typeof hidden === "undefined") {
            // not supported
        }
        else {
            document.addEventListener(visibilityChange, function() {
                console.log("hidden: " + document[hidden]);
                console.log(document[visibilityState]);

                switch (document[visibilityState]) {
                case "visible":
                    // visible
                    break;
                case "hidden":
                    // hidden
                    break;
                }
            }, false);
        }

        if (document[visibilityState] === "visible") {
            // visible
        }

    };  

Is it possible to append Series to rows of DataFrame without making a list first?

Something like this could work...

mydf.loc['newindex'] = myseries

Here is an example where I used it...

stats = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].describe()

stats
Out[32]: 
          bp_prob   ICD9_prob   meds_prob  regex_prob
count  171.000000  171.000000  171.000000  171.000000
mean     0.179946    0.059071    0.067020    0.126812
std      0.271546    0.142681    0.152560    0.207014
min      0.000000    0.000000    0.000000    0.000000
25%      0.000000    0.000000    0.000000    0.000000
50%      0.000000    0.000000    0.000000    0.013116
75%      0.309019    0.065248    0.066667    0.192954
max      1.000000    1.000000    1.000000    1.000000

medians = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].median()

stats.loc['median'] = medians

stats
Out[36]: 
           bp_prob   ICD9_prob   meds_prob  regex_prob
count   171.000000  171.000000  171.000000  171.000000
mean      0.179946    0.059071    0.067020    0.126812
std       0.271546    0.142681    0.152560    0.207014
min       0.000000    0.000000    0.000000    0.000000
25%       0.000000    0.000000    0.000000    0.000000
50%       0.000000    0.000000    0.000000    0.013116
75%       0.309019    0.065248    0.066667    0.192954
max       1.000000    1.000000    1.000000    1.000000
median    0.000000    0.000000    0.000000    0.013116

How to change a string into uppercase

To get upper case version of a string you can use str.upper:

s = 'sdsd'
s.upper()
#=> 'SDSD'

On the other hand string.ascii_uppercase is a string containing all ASCII letters in upper case:

import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

How to set opacity in parent div and not affect in child div?

You can't do that, unless you take the child out of the parent and place it via positioning.

The only way I know and it actually works, is to use a translucid image (.png with transparency) for the parent's background. The only disavantage is that you can't control the opacity via CSS, other than that it works!

$_POST not working. "Notice: Undefined index: username..."

first of all,

be sure that there is a post

if(isset($_POST['username'])) { 
    // check if the username has been set
}

second, and most importantly, sanitize the data, meaning that

$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";

is deadly dangerous, instead use

$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";

and please research the subject sql injection

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

What are the aspect ratios for all Android phone and tablet devices?

The Sony Tablet P is old, but it can switch between 32:15 and 32:30 for each app in landscape mode, and vice-versa in portrait mode, so that's a minimum range to aim for

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How to use external ".js" files

Note :- Do not use script tag in external JavaScript file.

<html>
<head>

</head>
<body>
    <p id="cn"> Click on the button to change the light button</p>
    <button type="button" onclick="changefont()">Click</button>

     <script src="external.js"></script>
</body>

External Java Script file:-

        function changefont()
            {

                var x = document.getElementById("cn");
                x.style.fontSize = "25px";           
                x.style.color = "red"; 
            }

Can we open pdf file using UIWebView on iOS?

WKWebView: I find this question to be the best place to let people know that they should start using WKWebview as UIWebView is now deprecated.

Objective C

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame];
webView.navigationDelegate = self;
NSURL *nsurl=[NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self.view addSubview:webView];

Swift

let myURLString = "https://www.example.com/document.pdf"
let url = NSURL(string: myURLString)
let request = NSURLRequest(URL: url!)  
let webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.loadRequest(request)
view.addSubview(webView)

I haven't copied this code directly from Xcode, so it might, it might contain some syntax error. Please check while using it.

Check If array is null or not in php

you can use

empty($result) 

to check if the main array is empty or not.

But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See http://www.php.net/manual/en/simplexmlelement.count.php

ex:

if (empty($result) || !isset($result['Tags'])) {
    return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
    return false;
}
return ($result['Tags']->count());

How to calculate a mod b in Python?

There's the % sign. It's not just for the remainder, it is the modulo operation.

The VMware Authorization Service is not running

type Services at search, then start Services

enter image description here

then start all VM services

enter image description here

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

You may get some information viewing it in assembly, but I think the easiest thing to do is fire up a virtual machine and see what it does. Make sure you have no open shares or anything like that that it can jump through though ;)

Formula to convert date to number

If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900

Screenprint 1

Screenprint 2

If your date is text and you need to convert it then DATEVALUE will do this:

Datevalue function

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

If you want to use it in plain SQL, I would let the store procedure fill a table or temp table with the resulting rows (or go for @Tony Andrews approach).
If you want to use @Thilo's solution, you have to loop the cursor using PL/SQL. Here an example: (I used a procedure instead of a function, like @Thilo did)

create or replace procedure myprocedure(retval in out sys_refcursor) is
begin
  open retval for
    select TABLE_NAME from user_tables;
end myprocedure;

 declare 
   myrefcur sys_refcursor;
   tablename user_tables.TABLE_NAME%type;
 begin
   myprocedure(myrefcur);
   loop
     fetch myrefcur into tablename;
     exit when myrefcur%notfound;
     dbms_output.put_line(tablename);
   end loop;
   close myrefcur;
 end;

How do I get a list of all subdomains of a domain?

robotex tools which are free will let you do this but they make you enter the ip of the domain first:

  1. find out the ip (there's a good ff plugin which does this but I can't post the link cos this is my first post here!)
  2. do an ip search on robotex: http://www.robtex.com/ip/
  3. in the results page that follows click on the domain you're interested in>
  4. you are taken to a page that lists all subdomains + a load of other information such as mail server info

C# naming convention for constants?

First, Hungarian Notation is the practice of using a prefix to display a parameter's data type or intended use. Microsoft's naming conventions for says no to Hungarian Notation http://en.wikipedia.org/wiki/Hungarian_notation http://msdn.microsoft.com/en-us/library/ms229045.aspx

Using UPPERCASE is not encouraged as stated here: Pascal Case is the acceptable convention and SCREAMING CAPS. http://en.wikibooks.org/wiki/C_Sharp_Programming/Naming

Microsoft also states here that UPPERCASE can be used if it is done to match the the existed scheme. http://msdn.microsoft.com/en-us/library/x2dbyw72.aspx

This pretty much sums it up.

Send array with Ajax to PHP script

dataString suggests the data is formatted in a string (and maybe delimted by a character).

$data = explode(",", $_POST['data']);
foreach($data as $d){
     echo $d;
}

if dataString is not a string but infact an array (what your question indicates) use JSON.

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

I've used Wiredesignz's MY_Language class with great success.

I've just published it on github, as I can't seem to find a trace of it anywhere.

https://github.com/meigwilym/CI_Language

My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.

Untrack files from git temporarily

To remove all Untrack files. Try this terminal command

 git clean -fdx

How do I call a specific Java method on a click/submit event of a specific button in JSP?

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
            myClass.method1();
        } else if (request.getParameter("button2") != null) {
            myClass.method2();
        } else if (request.getParameter("button3") != null) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

Alternatively, use <button type="submit"> instead of <input type="submit">, then you can give them all the same name, but an unique value. The value of the <button> won't be used as label, you can just specify that yourself as child.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <button type="submit" name="button" value="button1">Button 1</button>
    <button type="submit" name="button" value="button2">Button 2</button>
    <button type="submit" name="button" value="button3">Button 3</button>
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();
        String button = request.getParameter("button");

        if ("button1".equals(button)) {
            myClass.method1();
        } else if ("button2".equals(button)) {
            myClass.method2();
        } else if ("button3".equals(button)) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

See also:

Trying to SSH into an Amazon Ec2 instance - permission error

You are likely using the wrong username to login:

  • most Ubuntu images have a user ubuntu
  • Amazon's AMI is ec2-user
  • most Debian images have either root or admin

To login, you need to adjust your ssh command:

ssh -l USERNAME_HERE -i .ssh/yourkey.pem public-ec2-host

HTH

R cannot be resolved - Android error

Sometimes it helps when you manually create R.java file just simple empty R.java.

What is the difference between const and readonly in C#?

  • when to use const or readonly

    • const

      • compile-time constant: absolute constant, value is set during declaration, is in the IL code itself
    • readonly

      • run-time constant: can be set in the constructor/init via config file i.e. App.config, but once it initializes it can't be changed

How to delete and update a record in Hive

Yes, rightly said. Hive does not support UPDATE option. But the following alternative could be used to achieve the result:

Update records in a partitioned Hive table:

  1. The main table is assumed to be partitioned by some key.
  2. Load the incremental data (the data to be updated) to a staging table partitioned with the same keys as the main table.
  3. Join the two tables (main & staging tables) using a LEFT OUTER JOIN operation as below:

    insert overwrite table main_table partition (c,d) select t2.a, t2.b, t2.c,t2.d from staging_table t2 left outer join main_table t1 on t1.a=t2.a;

In the above example, the main_table & the staging_table are partitioned using the (c,d) keys. The tables are joined via a LEFT OUTER JOIN and the result is used to OVERWRITE the partitions in the main_table.

A similar approach could be used in the case of un-partitioned Hive table UPDATE operations too.

Log to the base 2 in python

>>> def log2( x ):
...     return math.log( x ) / math.log( 2 )
... 
>>> log2( 2 )
1.0
>>> log2( 4 )
2.0
>>> log2( 8 )
3.0
>>> log2( 2.4 )
1.2630344058337937
>>> 

Twitter Bootstrap - full width navbar

Just replace <div class="container"> with <div class="container-fluid">, which is the container with no margins on both sides.

I think this is the best solution because it avoids some useless overriding and makes use of built-in classes, it's clean.

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

LINQ orderby on date field in descending order

This statement will definitely help you:

env = env.OrderByDescending(c => c.ReportDate).ToList();

How do I restrict a float value to only two places after the decimal point in C?

If you just want to round the number for output purposes, then the "%.2f" format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:

#include <math.h>

float val = 37.777779;

float rounded_down = floorf(val * 100) / 100;   /* Result: 37.77 */
float nearest = roundf(val * 100) / 100;  /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100;      /* Result: 37.78 */

Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.

As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.

For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

Well this is because ArrayList resulting from Arrays.asList() is not of the type java.util.ArrayList . Arrays.asList() creates an ArrayList of type java.util.Arrays$ArrayList which does not extend java.util.ArrayList but only extends java.util.AbstractList

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Differences between ConstraintLayout and RelativeLayout

Relative Layout and Constraint Layout equivalent properties

Relative Layout and Constraint Layout equivalent properties

(1) Relative Layout:

android:layout_centerInParent="true"    

(1) Constraint Layout equivalent :

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"

(2) Relative Layout:

android:layout_centerHorizontal="true"

(2) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"

(3) Relative Layout:

android:layout_centerVertical="true"    

(3) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"

(4) Relative Layout:

android:layout_alignParentLeft="true"   

(4) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="parent"

(5) Relative Layout:

android:layout_alignParentStart="true"

(5) Constraint Layout equivalent:

app:layout_constraintStart_toStartOf="parent"

(6) Relative Layout:

android:layout_alignParentRight="true"

(6) Constraint Layout equivalent:

app:layout_constraintRight_toRightOf="parent"

(7) Relative Layout:

android:layout_alignParentEnd="true"    

(7) Constraint Layout equivalent:

app:layout_constraintEnd_toEndOf="parent"

(8) Relative Layout:

android:layout_alignParentTop="true"

(8) Constraint Layout equivalent:

app:layout_constraintTop_toTopOf="parent"

(9) Relative Layout:

android:layout_alignParentBottom="true" 

(9) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="parent"

(10) Relative Layout:

android:layout_alignStart="@id/view"

(10) Constraint Layout equivalent:

app:layout_constraintStart_toStartOf="@id/view"

(11) Relative Layout:

android:layout_alignLeft="@id/view" 

(11) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="@id/view"

(12) Relative Layout:

android:layout_alignEnd="@id/view"  

(12) Constraint Layout equivalent:

app:layout_constraintEnd_toEndOf="@id/view"

(13) Relative Layout:

android:layout_alignRight="@id/view"

(13) Constraint Layout equivalent:

app:layout_constraintRight_toRightOf="@id/view"

(14) Relative Layout:

android:layout_alignTop="@id/view"  

(14) Constraint Layout equivalent:

app:layout_constraintTop_toTopOf="@id/view"

(15) Relative Layout:

android:layout_alignBaseline="@id/view" 

(15) Constraint Layout equivalent:

app:layout_constraintBaseline_toBaselineOf="@id/view"

(16) Relative Layout:

android:layout_alignBottom="@id/view"

(16) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="@id/view"

(17) Relative Layout:

android:layout_toStartOf="@id/view"

(17) Constraint Layout equivalent:

app:layout_constraintEnd_toStartOf="@id/view"

(18) Relative Layout:

android:layout_toLeftOf="@id/view"  

(18) Constraint Layout equivalent:

app:layout_constraintRight_toLeftOf="@id/view"

(19) Relative Layout:

android:layout_toEndOf="@id/view"

(19) Constraint Layout equivalent:

app:layout_constraintStart_toEndOf="@id/view"

(20) Relative Layout:

android:layout_toRightOf="@id/view"

(20) Constraint Layout equivalent:

app:layout_constraintLeft_toRightOf="@id/view"

(21) Relative Layout:

android:layout_above="@id/view" 

(21) Constraint Layout equivalent:

app:layout_constraintBottom_toTopOf="@id/view"

(22) Relative Layout:

android:layout_below="@id/view" 

(22) Constraint Layout equivalent:

app:layout_constraintTop_toBottomOf="@id/view"

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

This is an old question with valuable answers, but I was still a bit confused until I found a real life example that shows the issue with 3NF. Maybe not suitable for an 8-year old child but hope it helps.

Tomorrow I'll meet the teachers of my eldest daughter in one of those quarterly parent/teachers meetings. Here's what my diary looks like (names and rooms have been changed):

Teacher   | Date             | Room
----------|------------------|-----
Mr Smith  | 2018-12-18 18:15 | A12 
Mr Jones  | 2018-12-18 18:30 | B10 
Ms Doe    | 2018-12-18 18:45 | C21 
Ms Rogers | 2018-12-18 19:00 | A08 

There's only one teacher per room and they never move. If you have a look, you'll see that: (1) for every attribute Teacher, Date, Room, we have only one value per row. (2) super-keys are: (Teacher, Date, Room), (Teacher, Date) and (Date, Room) and candidate keys are obviously (Teacher, Date) and (Date, Room).

(Teacher, Room) is not a superkey because I will complete the table next quarter and I may have a row like this one (Mr Smith did not move!):

Teacher  | Date             | Room
---------|------------------| ----
Mr Smith | 2019-03-19 18:15 | A12

What can we conclude? (1) is an informal but correct formulation of 1NF. From (2) we see that there is no "non prime attribute": 2NF and 3NF are given for free.

My diary is 3NF. Good! No. Not really because no data modeler would accept this in a DB schema. The Room attribute is dependant on the Teacher attribute (again: teachers do not move!) but the schema does not reflect this fact. What would a sane data modeler do? Split the table in two:

Teacher   | Date
----------|-----------------
Mr Smith  | 2018-12-18 18:15
Mr Jones  | 2018-12-18 18:30
Ms Doe    | 2018-12-18 18:45
Ms Rogers | 2018-12-18 19:00

And

Teacher   | Room
----------|-----
Mr Smith  | A12
Mr Jones  | B10
Ms Doe    | C21
Ms Rogers | A08

But 3NF does not deal with prime attributes dependencies. This is the issue: 3NF compliance is not enough to ensure a sound table schema design under some circumstances.

With BCNF, you don't care if the attribute is a prime attribute or not in 2NF and 3NF rules. For every non trivial dependency (subsets are obviously determined by their supersets), the determinant is a complete super key. In other words, nothing is determined by something else than a complete super key (excluding trivial FDs). (See other answers for formal definition).

As soon as Room depends on Teacher, Room must be a subset of Teacher (that's not the case) or Teacher must be a super key (that's not the case in my diary, but thats the case when you split the table).

To summarize: BNCF is more strict, but in my opinion easier to grasp, than 3NF:

  • in most of cases, BCNF is identical to 3NF;
  • in other cases, BCNF is what you think/hope 3NF is.

What's the best three-way merge tool?

KDiff3 open source, cross platform

Same interface for Linux and Windows, very smart algorithm for solving conflicts, regular expressions for automatically solving conflicts, integrate with ClearCase, SVN, Git, MS Visual Studio, editable merged file, compare directories

Its keyboard-navigation is great: ctrl-arrows to navigate the diffs, ctrl-1, 2, 3 to do the merging.

Also, see https://stackoverflow.com/a/2434482/42473

enter image description here

How can I mock requests and the response?

Just a helpful hint to those that are still struggling, converting from urllib or urllib2/urllib3 to requests AND trying to mock a response- I was getting a slightly confusing error when implementing my mock:

with requests.get(path, auth=HTTPBasicAuth('user', 'pass'), verify=False) as url:

AttributeError: __enter__

Well, of course, if I knew anything about how with works (I didn't), I'd know it was a vestigial, unnecessary context (from PEP 343). Unnecessary when using the requests library because it does basically the same thing for you under the hood. Just remove the with and use bare requests.get(...) and Bob's your uncle.

How to get the current time in Google spreadsheet using script editor?

Use the Date object provided by javascript. It's not unique or special to Google's scripting environment.

Initializing a two dimensional std::vector

There is no append method in std::vector, but if you want to make a vector containing A_NUMBER vectors of int, each of those containing other_number zeros, then you can do this:

std::vector<std::vector<int>> fog(A_NUMBER, std::vector<int>(OTHER_NUMBER));

What are the dark corners of Vim your mom never told you about?

Want an IDE?

:make will run the makefile in the current directory, parse the compiler output, you can then use :cn and :cp to step through the compiler errors opening each file and seeking to the line number in question.

:syntax on turns on vim's syntax highlighting.

Service has zero application (non-infrastructure) endpoints

I just ran into this issue and checked all of the above answers to make sure I wasn't missing anything obvious. Well, I had a semi-obvious issue. My casing of my classname in code and the classname I used in the configuration file didn't match.

For example: if the class name is CalculatorService and the configuration file refers to Calculatorservice ... you will get this error.

Select All distinct values in a column using LINQ

Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.

My (somewhat simple) code was:

public class Pair 
{ 
    public int id {get;set;}
    public string Arb {get;set;}
}

void Main()
{

    var theList = new List<Pair>();
    var randomiser = new Random();
    for (int count = 1; count < 10000; count++)
    {
        theList.Add(new Pair 
        {
            id = randomiser.Next(1, 50),
            Arb = "not used"
        });
    }

    var timer = new Stopwatch();
    timer.Start();
    var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);

    timer.Start();
    var otherDistinct = theList.Select(p => p.id).Distinct();
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);
}

How to install gdb (debugger) in Mac OSX El Capitan?

It seems that MacPorts could be installed in El Capitan right now: https://www.macports.org/install.php Then you probably can install gdb by link you mentioned.

extract date only from given timestamp in oracle sql

Convert Timestamp to Date as mentioned below, it will work for sure -

select TO_DATE(TO_CHAR(TO_TIMESTAMP ('2015-04-15 18:00:22.000', 'YYYY-MM-DD HH24:MI:SS.FF'),'MM/DD/YYYY HH24:MI:SS'),'MM/DD/YYYY HH24:MI:SS') dt from dual

How to set up java logging using a properties file? (java.util.logging)

Logger log = Logger.getLogger("myApp");
log.setLevel(Level.ALL);
log.info("initializing - trying to load configuration file ...");

//Properties preferences = new Properties();
try {
    //FileInputStream configFile = new //FileInputStream("/path/to/app.properties");
    //preferences.load(configFile);
    InputStream configFile = myApp.class.getResourceAsStream("app.properties");
    LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException ex)
{
    System.out.println("WARNING: Could not open configuration file");
    System.out.println("WARNING: Logging not configured (console output only)");
}
log.info("starting myApp");

this is working..:) you have to pass InputStream in readConfiguration().

align textbox and text/labels in html?

I have found better option,

<style type="text/css">
    .form {
        margin: 0 auto;
        width: 210px;
    }
    .form label{
        display: inline-block;
        text-align: right;
        float: left;
    }
    .form input{
        display: inline-block;
        text-align: left;
        float: right;
    }
</style>

Demo here: https://jsfiddle.net/durtpwvx/

Ambiguous overload call to abs(double)

Use fabs() instead of abs(), it's the same but for floats instead of integers.

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

As the error code says, "no alternative certificate subject name matches target host name" - so there is an issue with the SSL certificate.

The certificate should include SAN, and only SAN will be used. Some browsers ignore the deprecated Common Name.

RFC 2818 clearly states "If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead."

What is the best way to add a value to an array in state

For now, this is the best way.

this.setState(previousState => ({
    myArray: [...previousState.myArray, 'new value']
}));

What is the difference between Hibernate and Spring Data JPA

Spring Data is a convenience library on top of JPA that abstracts away many things and brings Spring magic (like it or not) to the persistence store access. It is primarily used for working with relational databases. In short, it allows you to declare interfaces that have methods like findByNameOrderByAge(String name); that will be parsed in runtime and converted into appropriate JPA queries.

Its placement atop of JPA makes its use tempting for:

  1. Rookie developers who don't know SQL or know it badly. This is a recipe for disaster but they can get away with it if the project is trivial.

  2. Experienced engineers who know what they do and want to spindle up things fast. This might be a viable strategy (but read further).

From my experience with Spring Data, its magic is too much (this is applicable to Spring in general). I started to use it heavily in one project and eventually hit several corner cases where I couldn't get the library out of my way and ended up with ugly workarounds. Later I read other users' complaints and realized that these issues are typical for Spring Data. For example, check this issue that led to hours of investigation/swearing:

 public TourAccommodationRate createTourAccommodationRate(
        @RequestBody TourAccommodationRate tourAccommodationRate
    ) {
        if (tourAccommodationRate.getId() != null) {
            throw new BadRequestException("id MUST NOT be specified in a body during entry creation");
        }

        // This is an ugly hack required for the Room slim model to work. The problem stems from the fact that
        // when we send a child entity having the many-to-many (M:N) relation to the containing entity, its
        // information is not fetched. As a result, we get NPEs when trying to access all but its Id in the
        // code creating the corresponding slim model. By detaching the entity from the persistence context we
        // force the ORM to re-fetch it from the database instead of taking it from the cache

        tourAccommodationRateRepository.save(tourAccommodationRate);
        entityManager.detach(tourAccommodationRate);
        return tourAccommodationRateRepository.findOne(tourAccommodationRate.getId());
    }

I ended up going lower level and started using JDBI - a nice library with just enough "magic" to save you from the boilerplate. With it, you have complete control over SQL queries and almost never have to fight the library.

What is the difference between DSA and RSA?

Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

How to tell if a JavaScript function is defined

If you look at the source of the library @Venkat Sudheer Reddy Aedama mentioned, underscorejs, you can see this:

_.isFunction = function(obj) {
  return typeof obj == 'function' || false;
};

This is just my HINT, HINT answer :>

What is a reasonable code coverage % for unit tests (and why)?

Depending on the criticality of the code, anywhere from 75%-85% is a good rule of thumb. Shipping code should definitely be tested more thoroughly than in house utilities, etc.

How to check if two arrays are equal with JavaScript?

Using map() and reduce():

function arraysEqual (a1, a2) {
    return a1 === a2 || (
        a1 !== null && a2 !== null &&
        a1.length === a2.length &&
        a1
            .map(function (val, idx) { return val === a2[idx]; })
            .reduce(function (prev, cur) { return prev && cur; }, true)
    );
}

List passed by ref - help me explain this behaviour

While I agree with what everyone has said above. I have a different take on this code. Basically you're assigning the new list to the local variable myList not the global. if you change the signature of ChangeList(List myList) to private void ChangeList() you'll see the output of 3, 4.

Here's my reasoning... Even though list is passed by reference, think of it as passing a pointer variable by value When you call ChangeList(myList) you're passing the pointer to (Global)myList. Now this is stored in the (local)myList variable. So now your (local)myList and (global)myList are pointing to the same list. Now you do a sort => it works because (local)myList is referencing the original (global)myList Next you create a new list and assign the pointer to that your (local)myList. But as soon as the function exits the (local)myList variable is destroyed. HTH

class Test
{
    List<int> myList = new List<int>();
    public void TestMethod()
    {

        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList();

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList()
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}

ASP.NET Core Get Json Array using IConfiguration

If you have array of complex JSON objects like this:

{
  "MySettings": {
    "MyValues": [
      { "Key": "Key1", "Value":  "Value1" },
      { "Key": "Key2", "Value":  "Value2" }
    ]
  }
}

You can retrieve settings this way:

var valuesSection = configuration.GetSection("MySettings:MyValues");
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
    var key = section.GetValue<string>("Key");
    var value = section.GetValue<string>("Value");
}

Create listview in fragment android

Instead:

public class PhotosFragment extends Fragment

You can use:

public class PhotosFragment extends ListFragment

It change the methods

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayList<ListviewContactItem> listContact = GetlistContact();
        setAdapter(new ListviewContactAdapter(getActivity(), listContact));
    }

onActivityCreated is void and you didn't need to return a view like in onCreateView

You can see an example here

How to click an element in Selenium WebDriver using JavaScript

You can't use WebDriver to do it in JavaScript, as WebDriver is a Java tool. However, you can execute JavaScript from Java using WebDriver, and you could call some JavaScript code that clicks a particular button.

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('gbqfb').click()");

Getting last month's date in php

echo date('Y',strtotime("-1 year"));        //last year<br>
echo date('d',strtotime("-1 day"));     //last day<br>
echo date('m',strtotime("-1 month"));       //last month<br>

replace \n and \r\n with <br /> in java

That should work, but don't kill yourself trying to figure it out. Just use 2 passes.

str  = str.replaceAll("(\r\n)", "<br />");
str  = str.replaceAll("(\n)", "<br />");

Disclaimer: this is not very efficient.

adding text to an existing text element in javascript via DOM

_x000D_
_x000D_
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");

t.appendChild(y);
_x000D_
<p id="p">This is some text</p>
_x000D_
_x000D_
_x000D_

How to run a PowerShell script without displaying a window?

Wait until Powershell is executed and get the result in vbs

This is an improved version of the Omegastripes code Hide command prompt window when using Exec()

Splits the confused responses from cmd.exe into an array instead of putting everything into a hard-to-parse string.

In addition, if an error occurs during the execution of cmd.exe, a message about its occurrence will become known in vbs.

Option Explicit
Sub RunCScriptHidden()
    strSignature = Left(CreateObject("Scriptlet.TypeLib").Guid, 38)
    GetObject("new:{C08AFD90-F2A1-11D1-8455-00A0C91F3880}").putProperty strSignature, Me
    objShell.Run ("""" & Replace(LCase(WScript.FullName), "wscript", "cscript") & """ //nologo """ & WScript.ScriptFullName & """ ""/signature:" & strSignature & """"), 0, True
End Sub
Sub WshShellExecCmd()
    For Each objWnd In CreateObject("Shell.Application").Windows
        If IsObject(objWnd.getProperty(WScript.Arguments.Named("signature"))) Then Exit For
    Next
    Set objParent = objWnd.getProperty(WScript.Arguments.Named("signature"))
    objWnd.Quit
    'objParent.strRes = CreateObject("WScript.Shell").Exec(objParent.strCmd).StdOut.ReadAll() 'simple solution
    Set exec = CreateObject("WScript.Shell").Exec(objParent.strCmd)
    While exec.Status = WshRunning
        WScript.Sleep 20
    Wend
    Dim err
    If exec.ExitCode = WshFailed Then
        err = exec.StdErr.ReadAll
    Else
        output = Split(exec.StdOut.ReadAll,Chr(10))
    End If
    If err="" Then
        objParent.strRes = output(UBound(output)-1) 'array of results, you can: output(0) Join(output) - Usually needed is the last
    Else
        objParent.wowError = err
    End If
WScript.Quit
End Sub
Const WshRunning = 0,WshFailed = 1:Dim i,name,objShell
Dim strCmd, strRes, objWnd, objParent, strSignature, wowError, output, exec

Set objShell = WScript.CreateObject("WScript.Shell"):wowError=False
strCmd = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass Write-Host Hello-World."
If WScript.Arguments.Named.Exists("signature") Then WshShellExecCmd
RunCScriptHidden
If wowError=False Then
    objShell.popup(strRes)
Else
    objShell.popup("Error=" & wowError)
End If

How to make inline plots in Jupyter Notebook larger?

The default figure size (in inches) is controlled by

matplotlib.rcParams['figure.figsize'] = [width, height]

For example:

import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [10, 5]

creates a figure with 10 (width) x 5 (height) inches

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

I recently started receiving this error inside of my internal NLog failures log, with Visual Studio 2013. The solution has been using NLog v2.0.0 for several years. Within the last month, our main log stopped working. To fix this I updated NLog to the newest version (v3.1.0) via Nuget. The security exception is now gone and ALL of the log messages are appearing again.

Additionally, I later found another Security exception and was able to fix it by following the instructions on this post in another thread.

Java: Multiple class declarations in one file

My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.

As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)

How to use SVN, Branch? Tag? Trunk?

A lot of good comments here, but something that hasn't been mentioned is commit messages. These should be mandatory and meaningful. Especially with branching/merging. This will allow you to keep track of what changes are relevant to which bugs features.

for example svn commit . -m 'bug #201 fixed y2k bug in code' will tell anyone who looks at the history what that revision was for.

Some bug tracking systems (eg trac) can look in the repository for these messages and associate them with the tickets. Which makes working out what changes are associated with each ticket very easy.

List files committed for a revision

svn log --verbose -r 42

How to verify element present or visible in selenium 2 (Selenium WebDriver)

webDriver.findElement(By.xpath("//*[@id='element']")).isDisplayed();

Android studio Gradle icon error, Manifest Merger

I had this problem changing the icon from drawable to mipmap.

I only missed the line

tools:replace="android:icon"

in the manifest.

How to make a jquery function call after "X" seconds

If you could show the actual page, we, possibly, could help you better.

If you want to trigger the button only after the iframe is loaded, you might want to check if it has been loaded or use the iframe.onload:

<iframe .... onload='buttonWhatever(); '></iframe>


<script type="text/javascript">

    function buttonWhatever() {
        $("#<%=Button1.ClientID%>").click(function (event) {
            $('#<%=TextBox1.ClientID%>').change(function () {
                $('#various3').attr('href', $(this).val());
            });
            $("#<%=Button2.ClientID%>").click();
        });

        function showStickySuccessToast() {
            $().toastmessage('showToast', {
                text: 'Finished Processing!',
                sticky: false,
                position: 'middle-center',
                type: 'success',
                closeText: '',
                close: function () { }
            });
        }
    }

</script>

How to pretty print nested dictionaries?

Here's something that will print any sort of nested dictionary, while keeping track of the "parent" dictionaries along the way.

dicList = list()

def prettierPrint(dic, dicList):
count = 0
for key, value in dic.iteritems():
    count+=1
    if str(value) == 'OrderedDict()':
        value = None
    if not isinstance(value, dict):
        print str(key) + ": " + str(value)
        print str(key) + ' was found in the following path:',
        print dicList
        print '\n'
    elif isinstance(value, dict):
        dicList.append(key)
        prettierPrint(value, dicList)
    if dicList:
         if count == len(dic):
             dicList.pop()
             count = 0

prettierPrint(dicExample, dicList)

This is a good starting point for printing according to different formats, like the one specified in OP. All you really need to do is operations around the Print blocks. Note that it looks to see if the value is 'OrderedDict()'. Depending on whether you're using something from Container datatypes Collections, you should make these sort of fail-safes so the elif block doesn't see it as an additional dictionary due to its name. As of now, an example dictionary like

example_dict = {'key1': 'value1',
            'key2': 'value2',
            'key3': {'key3a': 'value3a'},
            'key4': {'key4a': {'key4aa': 'value4aa',
                               'key4ab': 'value4ab',
                               'key4ac': 'value4ac'},
                     'key4b': 'value4b'}

will print

key3a: value3a
key3a was found in the following path: ['key3']

key2: value2
key2 was found in the following path: []

key1: value1
key1 was found in the following path: []

key4ab: value4ab
key4ab was found in the following path: ['key4', 'key4a']

key4ac: value4ac
key4ac was found in the following path: ['key4', 'key4a']

key4aa: value4aa
key4aa was found in the following path: ['key4', 'key4a']

key4b: value4b
key4b was found in the following path: ['key4']

~altering code to fit the question's format~

lastDict = list()
dicList = list()
def prettierPrint(dic, dicList):
    global lastDict
    count = 0
    for key, value in dic.iteritems():
        count+=1
        if str(value) == 'OrderedDict()':
            value = None
        if not isinstance(value, dict):
            if lastDict == dicList:
                sameParents = True
            else:
                sameParents = False

            if dicList and sameParents is not True:
                spacing = ' ' * len(str(dicList))
                print dicList
                print spacing,
                print str(value)

            if dicList and sameParents is True:
                print spacing,
                print str(value)
            lastDict = list(dicList)

        elif isinstance(value, dict):
            dicList.append(key)
            prettierPrint(value, dicList)

        if dicList:
             if count == len(dic):
                 dicList.pop()
                 count = 0

Using the same example code, it will print the following:

['key3']
         value3a
['key4', 'key4a']
                  value4ab
                  value4ac
                  value4aa
['key4']
         value4b

This isn't exactly what is requested in OP. The difference is that a parent^n is still printed, instead of being absent and replaced with white-space. To get to OP's format, you'll need to do something like the following: iteratively compare dicList with the lastDict. You can do this by making a new dictionary and copying dicList's content to it, checking if i in the copied dictionary is the same as i in lastDict, and -- if it is -- writing whitespace to that i position using the string multiplier function.

Simple way to measure cell execution time in ipython notebook

you may also want to look in to python's profiling magic command %prunwhich gives something like -

def sum_of_lists(N):
    total = 0
    for i in range(5):
        L = [j ^ (j >> i) for j in range(N)]
        total += sum(L)
    return total

then

%prun sum_of_lists(1000000)

will return

14 function calls in 0.714 seconds  

Ordered by: internal time      

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    5    0.599    0.120    0.599    0.120 <ipython-input-19>:4(<listcomp>)
    5    0.064    0.013    0.064    0.013 {built-in method sum}
    1    0.036    0.036    0.699    0.699 <ipython-input-19>:1(sum_of_lists)
    1    0.014    0.014    0.714    0.714 <string>:1(<module>)
    1    0.000    0.000    0.714    0.714 {built-in method exec}

I find it useful when working with large chunks of code.

C pointer to array/array of pointers disambiguation

In pointer to an integer if pointer is incremented then it goes next integer.

in array of pointer if pointer is incremented it jumps to next array

'mvn' is not recognized as an internal or external command, operable program or batch file

Here is the best Maven-Environment Setup tutorial for Windows, Unix and Mac Operating systems.

But in the last you have to set value of PATH variable as ";%M2_HOME%\bin" instead of "%M2%", because PATH variable is not able to reduce the value using "%M2%"

What is it exactly a BLOB in a DBMS context

BLOB :

BLOB (Binary Large Object) is a large object data type in the database system. BLOB could store a large chunk of data, document types and even media files like audio or video files. BLOB fields allocate space only whenever the content in the field is utilized. BLOB allocates spaces in Giga Bytes.

USAGE OF BLOB :

You can write a binary large object (BLOB) to a database as either binary or character data, depending on the type of field at your data source. To write a BLOB value to your database, issue the appropriate INSERT or UPDATE statement and pass the BLOB value as an input parameter. If your BLOB is stored as text, such as a SQL Server text field, you can pass the BLOB as a string parameter. If the BLOB is stored in binary format, such as a SQL Server image field, you can pass an array of type byte as a binary parameter.

A useful link : Storing documents as BLOB in Database - Any disadvantages ?

enum Values to NSString (iOS)

I found this website (from which the example below is taken) which provides an elegant solution to this problem. The original posting though comes from this StackOverflow answer.

// Place this in your .h file, outside the @interface block
typedef enum {
    JPG,
    PNG,
    GIF,
    PVR
} kImageType;
#define kImageTypeArray @"JPEG", @"PNG", @"GIF", @"PowerVR", nil

...

// Place this in the .m file, inside the @implementation block
// A method to convert an enum to string
-(NSString*) imageTypeEnumToString:(kImageType)enumVal
{
    NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
    return [imageTypeArray objectAtIndex:enumVal];
}

// A method to retrieve the int value from the NSArray of NSStrings
-(kImageType) imageTypeStringToEnum:(NSString*)strVal
{
    NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
    NSUInteger n = [imageTypeArray indexOfObject:strVal];
    if(n < 1) n = JPG;
    return (kImageType) n;
}

How do you display JavaScript datetime in 12 hour AM/PM format?

If you don't need to print the am/pm, I found the following nice and concise:

var now = new Date();
var hours = now.getHours() % 12 || 12;  // 12h instead of 24h, with 12 instead of 0. 

This is based off @bbrame's answer.

Why check both isset() and !empty()

This is completely redundant. empty is more or less shorthand for !isset($foo) || !$foo, and !empty is analogous to isset($foo) && $foo. I.e. empty does the reverse thing of isset plus an additional check for the truthiness of a value.

Or in other words, empty is the same as !$foo, but doesn't throw warnings if the variable doesn't exist. That's the main point of this function: do a boolean comparison without worrying about the variable being set.

The manual puts it like this:

empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.

You can simply use !empty($vars[1]) here.

MySQL SELECT query string matching

Incorrect:

SELECT * FROM customers WHERE name LIKE '%Bob Smith%';

Instead:

select count(*)
from rearp.customers c
where c.name  LIKE '%Bob smith.8%';

select count will just query (totals)

C will link the db.table to the names row you need this to index

LIKE should be obvs

8 will call all references in DB 8 or less (not really needed but i like neatness)

Fully backup a git repo?

You can backup the git repo with git-copy at minimum storage size.

git copy /path/to/project /backup/project.repo.backup

Then you can restore your project with git clone

git clone /backup/project.repo.backup project

Write to rails console

puts or p is a good start to do that.

p "asd"       # => "asd"
puts "asd"    # => asd

here is more information about that: http://www.ruby-doc.org/core-1.9.3/ARGF.html

Why is SQL Server 2008 Management Studio Intellisense not working?

Here is the official word on this from MS.

http://support.microsoft.com/kb/2531482

Their solution is the same as above, install the SQL Server 2008 R2 updates with the version 10.50.1777.0.

http://support.microsoft.com/kb/2507770

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

PYTHON 3

import urllib.request

wp = urllib.request.urlopen("http://example.com")

pw = wp.read()

print(pw)

PYTHON 2

import urllib

 import sys

 wp = urllib.urlopen("http://example.com")

 for line in wp:

     sys.stdout.write(line)

While I have tested both the Codes in respective versions.

SQL permissions for roles

USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO  ---- Assign Role To users -------  CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username'  ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO 

TCPDF not render all CSS properties

At the moment I write this, TCPDF only supports padding for tables.

Link to their forum page with that information

What does (function($) {})(jQuery); mean?

Just small addition to explanation

This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:

(function($) {
  // do something
})(jQuery);

this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $.

Set EditText cursor color

Another simple solution would be to go to res>values>colors.xml in your project folder and edit the value of the color accent to the color you prefer

<color name="colorAccent">#000000</color>

The code above changes your cursor to black.

Where can I download IntelliJ IDEA Color Schemes?

If you're just looking for a dark color scheme for IntelliJ IDEA, this is the first link I get in a Google search:

Dark Pastels theme for IntelliJ IDEA Dark Pastels theme for IntelliJ IDEA

Of course, you can tweak either of these two schemes to your satisfaction. Don't feel like you have to stick to the fonts and the colors that the original authors have chosen. We programmers don't get nearly enough change to try our hand at interior decorating to pass up this opportunity.

Is there any reason these won't work in the version you have? As best I can tell, you can simply import any theme that you want.

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

PUT

$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

POST

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

GET See @Dan H answer

DELETE

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

Forcing a postback

You can manually call the method invoked by PostBack from the Page_Load event:

public void Page_Load(object sender, EventArgs e)
{
    MyPostBackMethod(sender, e);
}

But if you mean if you can have the Page.IsPostBack property set to true without real post back, then the answer is no.

IntelliJ: Error:java: error: release version 5 not supported

In IntelliJ, the default maven compiler version is less than version 5, which is not supported, so we have to manually change the version of the maven compiler.

We have two ways to define version.

First way:

<properties>
  <maven.compiler.target>1.8</maven.compiler.target>
  <maven.compiler.source>1.8</maven.compiler.source>
</properties>

Second way:

<build>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
            <source>8</source>
            <target>8</target>
        </configuration>
    </plugin>
  </plugins>
</build>

Multiple Where clauses in Lambda expressions

Maybe

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty)
    .Where(l => l.InternalName != string.Empty)

?

You can probably also put it in the same where clause:

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty && l.InternalName != string.Empty)

Why is it bad practice to call System.gc()?

In my experience, using System.gc() is effectively a platform-specific form of optimization (where "platform" is the combination of hardware architecture, OS, JVM version and possible more runtime parameters such as RAM available), because its behaviour, while roughly predictable on a specific platform, can (and will) vary considerably between platforms.

Yes, there are situations where System.gc() will improve (perceived) performance. On example is if delays are tolerable in some parts of your app, but not in others (the game example cited above, where you want GC to happen at the start of a level, not during the level).

However, whether it will help or hurt (or do nothing) is highly dependent on the platform (as defined above).

So I think it is valid as a last-resort platform-specific optimization (i.e. if other performance optimizations are not enough). But you should never call it just because you believe it might help(without specific benchmarks), because chances are it will not.

How do I make CMake output into a 'bin' dir?

$ cat CMakeLists.txt
project (hello)
set(EXECUTABLE_OUTPUT_PATH "bin")
add_executable (hello hello.c)

Oracle date format picture ends before converting entire input string

I had this error today and discovered it was an incorrectly-formatted year...

select * from es_timeexpense where parsedate > to_date('12/3/2018', 'MM/dd/yyy')

Notice the year has only three 'y's. It should have 4.

Double-check your format.

how to save and read array of array in NSUserdefaults in swift?

Try this.

To get the data from the UserDefaults.

var defaults = NSUserDefaults.standardUserDefaults()
var dict : NSDictionary = ["key":"value"]
var array1: NSArray = dict.allValues // Create a dictionary and assign that to this array
defaults.setObject(array1, forkey : "MyKey")

var myarray : NSArray = defaults.objectForKey("MyKey") as NSArray
println(myarray)

Copy multiple files in Python

import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below

dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")

for filename in os.listdir(dir_src):
    if filename.endswith('.txt'):
        shutil.copy( dir_src + filename, dir_dst)
    print(filename)

Node.js global proxy setting

replace {userid} and {password} with your id and password in your organization or login to your machine.

npm config set proxy http://{userid}:{password}@proxyip:8080/
npm config set https-proxy http://{userid}:{password}@proxyip:8080/
npm config set http-proxy http://{userid}:{password}@proxyip:8080/
strict-ssl=false

Can't install Scipy through pip

After opening up an issue with the SciPy team, we found that you need to upgrade pip with:

pip install --upgrade pip

And in Python 3 this works:

python3 -m pip install --upgrade pip

for SciPy to install properly. Why? Because:

Older versions of pip have to be told to use wheels, IIRC with --use-wheel. Or you can upgrade pip itself, then it should pick up the wheels.

Upgrading pip solves the issue, but you might be able to just use the --use-wheel flag as well.

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

Overlaying a DIV On Top Of HTML 5 Video

Here's an example that will center the content within the parent div. This also makes sure the overlay starts at the edge of the video, even when centered.

<div class="outer-container">
    <div class="inner-container">
        <div class="video-overlay">Bug Buck Bunny - Trailer</div>
        <video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" controls autoplay loop></video>
    </div>
</div>

with css as

.outer-container {
    border: 1px dotted black;
    width: 100%;
    height: 100%;
    text-align: center;
}
.inner-container {
    border: 1px solid black;
    display: inline-block;
    position: relative;
}
.video-overlay {
    position: absolute;
    left: 0px;
    top: 0px;
    margin: 10px;
    padding: 5px 5px;
    font-size: 20px;
    font-family: Helvetica;
    color: #FFF;
    background-color: rgba(50, 50, 50, 0.3);
}
video {
    width: 100%;
    height: 100%;
}

here's the jsfiddle https://jsfiddle.net/dyrepk2x/2/

Hope that helps :)

fatal: bad default revision 'HEAD'

Not committed yet?

It is a orphan branch if it has no commit.

How to convert integer to string in C?

That's because itoa isn't a standard function. Try snprintf instead.

char str[LEN];
snprintf(str, LEN, "%d", 42);

JavaScript Nested function

Function-instantiation is allowed inside and outside of functions. Inside those functions, just like variables, the nested functions are local and therefore cannot be obtained from the outside scope.

function foo() {
    function bar() {
        return 1;
    }
    return bar();
}

foo manipulates bar within itself. bar cannot be touched from the outer scope unless it is defined in the outer scope.

So this will not work:

function foo() {
    function bar() {
        return 1;
    }
}

bar(); // throws error: bar is not defined

In git, what is the difference between merge --squash and rebase?

Both git merge --squash and git rebase --interactive can produce a "squashed" commit.
But they serve different purposes.

will produce a squashed commit on the destination branch, without marking any merge relationship.
(Note: it does not produce a commit right away: you need an additional git commit -m "squash branch")
This is useful if you want to throw away the source branch completely, going from (schema taken from SO question):

 git checkout stable

      X                   stable
     /                   
a---b---c---d---e---f---g tmp

to:

git merge --squash tmp
git commit -m "squash tmp"

      X-------------------G stable
     /                   
a---b---c---d---e---f---g tmp

and then deleting tmp branch.


Note: git merge has a --commit option, but it cannot be used with --squash. It was never possible to use --commit and --squash together.
Since Git 2.22.1 (Q3 2019), this incompatibility is made explicit:

See commit 1d14d0c (24 May 2019) by Vishal Verma (reloadbrain).
(Merged by Junio C Hamano -- gitster -- in commit 33f2790, 25 Jul 2019)

merge: refuse --commit with --squash

Previously, when --squash was supplied, 'option_commit' was silently dropped. This could have been surprising to a user who tried to override the no-commit behavior of squash using --commit explicitly.

git/git builtin/merge.c#cmd_merge() now includes:

if (option_commit > 0)
    die(_("You cannot combine --squash with --commit."));

replays some or all of your commits on a new base, allowing you to squash (or more recently "fix up", see this SO question), going directly to:

git checkout tmp
git rebase -i stable

      stable
      X-------------------G tmp
     /                     
a---b

If you choose to squash all commits of tmp (but, contrary to merge --squash, you can choose to replay some, and squashing others).

So the differences are:

  • squash does not touch your source branch (tmp here) and creates a single commit where you want.
  • rebase allows you to go on on the same source branch (still tmp) with:
    • a new base
    • a cleaner history

Sum values from an array of key-value pairs in JavaScript

You could use the Array.reduce method:

_x000D_
_x000D_
const myData = [_x000D_
  ['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],_x000D_
  ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], _x000D_
  ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], _x000D_
  ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]_x000D_
];_x000D_
const sum = myData_x000D_
  .map( v => v[1] )                                _x000D_
  .reduce( (sum, current) => sum + current, 0 );_x000D_
  _x000D_
console.log(sum);
_x000D_
_x000D_
_x000D_

See MDN

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

How can I start and check my MySQL log?

Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html

calling a java servlet from javascript

var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
  window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});

IE8 css selector

I'm not going to get in a debate about whether or not this method should be used, but this will let you set specific css attributes for IE8-9 only (note: it is not a selector, so a bit different than what you asked):

Use '\0/' after each css declaration, so:

#nav li ul  {
  left: -39px\0/ !important;
}

And to build off another answer, you can do this to assign variou styles to IE6, IE7, and IE8:

#nav li ul  {
   *left: -7px    !important; /* IE 7 (IE6 also uses this, so put it first) */
   _left: -6px    !important; /* IE 6 */
    left: -8px\0/ !important; /* IE 8-9 */
}

source: http://dimox.net/personal-css-hacks-for-ie6-ie7-ie8/

The simplest way to comma-delimit a list?

Based on Java's List toString implementation:

Iterator i = list.iterator();
for (;;) {
  sb.append(i.next());
  if (! i.hasNext()) break;
  ab.append(", ");
}

It uses a grammar like this:

List --> (Item , )* Item

By being last-based instead of first-based, it can check for skip-comma with the same test to check for end-of-list. I think this one is very elegant, but I'm not sure about clarity.

Capturing a single image from my webcam in Java or Python

import cv2
camera = cv2.VideoCapture(0)
while True:
    return_value,image = camera.read()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    cv2.imshow('image',gray)
    if cv2.waitKey(1)& 0xFF == ord('s'):
        cv2.imwrite('test.jpg',image)
        break
camera.release()
cv2.destroyAllWindows()

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

Is the 'as' keyword required in Oracle to define an alias?

AS without double quotations is good.

SELECT employee_id,department_id AS department
FROM employees
order by department

--ok--

SELECT employee_id,department_id AS "department"
FROM employees
order by department

--error on oracle--

so better to use AS without double quotation if you use ORDER BY clause

How to compare different branches in Visual Studio Code

It's now possible by using the githistory extension.

Here's a small trick though: You can compare the latest commits from each branch and that would be the same as comparing two branches side by side or creating a PR.

Here's how to do that using githistory extension:

  1. Open githistory
  2. Pick the latest commit from your current branch by clicking on "Git Commit Icon" → (Usually it should be latest commit it the list). From the opened dropdown menu click on "Select this commit".
  3. Pick the latest commit from the branch you want to compare to by clicking "Git Commit Icon".
  4. As a result, the dropdown should appear with a few options → Select the last option that says "Compare with SHA" and you'll see the diff.

Save PHP variables to a text file

This should do what you want, but without more context I can't tell for sure.

Writing $text to a file:

$text = "Anything";
$var_str = var_export($text, true);
$var = "<?php\n\n\$text = $var_str;\n\n?>";
file_put_contents('filename.php', $var);

Retrieving it again:

include 'filename.php';
echo $text;

How to align texts inside of an input?

If you want to get it aligned to the right after the text looses focus you can try to use the direction modifier. This will show the right part of the text after loosing focus. e.g. useful if you want to show the file name in a large path.

_x000D_
_x000D_
input.rightAligned {_x000D_
  direction:ltr;_x000D_
  overflow:hidden;_x000D_
}_x000D_
input.rightAligned:not(:focus) {_x000D_
  direction:rtl;_x000D_
  text-align: left;_x000D_
  unicode-bidi: plaintext;_x000D_
  text-overflow: ellipsis;_x000D_
}
_x000D_
<form>_x000D_
    <input type="text" class="rightAligned" name="name" value="">_x000D_
</form>
_x000D_
_x000D_
_x000D_

The not selector is currently well supported : Browser support

Cache an HTTP 'Get' service response in AngularJS?

An easier way to do this in the current stable version (1.0.6) requires a lot less code.

After setting up your module add a factory:

var app = angular.module('myApp', []);
// Configure routes and controllers and views associated with them.
app.config(function ($routeProvider) {
    // route setups
});
app.factory('MyCache', function ($cacheFactory) {
    return $cacheFactory('myCache');
});

Now you can pass this into your controller:

app.controller('MyController', function ($scope, $http, MyCache) {
    $http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
        // stuff with results
    });
});

One downside is that the key names are also setup automatically, which could make clearing them tricky. Hopefully they'll add in some way to get key names.

Test process.env with Jest

You can use the setupFiles feature of the Jest configuration. As the documentation said that,

A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.

  1. npm install dotenv dotenv that uses to access environment variable.

  2. Create your .env file to the root directory of your application and add this line into it:

    #.env
    APP_PORT=8080
    
  3. Create your custom module file as its name being someModuleForTest.js and add this line into it:

    // someModuleForTest.js
    require("dotenv").config()
    
  4. Update your jest.config.js file like this:

    module.exports = {
      setupFiles: ["./someModuleForTest"]
    }
    
  5. You can access an environment variable within all test blocks.

    test("Some test name", () => {
      expect(process.env.APP_PORT).toBe("8080")
    })
    

How to delete a workspace in Perforce (using p4v)?

From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.

To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.

In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.

TypeScript: Interfaces vs Types

TLDR;

My personal convention, which I describe below, is this:

Always prefer interface over type.

When to use type:

  • Use type when defining an alias for primitive types (string, boolean, number, bigint, symbol, etc)
  • Use type when defining tuple types
  • Use type when defining function types
  • Use type when defining a union
  • Use type when trying to overload functions in object types via composition
  • Use type when needing to take advantage of mapped types

When to use interface:

  • Use interface for all object types where using type is not required (see above)
  • Use interface when you want to take advatange of declaration merging.

Primitive types

The easiest difference to see between type and interface is that only type can be used to alias a primitive:

type Nullish = null | undefined;
type Fruit = 'apple' | 'pear' | 'orange';
type Num = number | bigint;

None of these examples are possible to achieve with interfaces.

When providing a type alias for a primitive value, use the type keyword.

Tuple types

Tuples can only be typed via the type keyword:

type row = [colOne: number, colTwo: string];

Use the type keyword when providing types for tuples.

Function types

Functions can be typed by both the type and interface keywords:

// via type
type Sum = (x: number, y: number) => number;

// via interface
interface Sum {
  (x: number, y: number): number;
}

Since the same effect can be achieved either way, the rule will be to use type in these scenarios since it's a little easier to read (and less verbose).

Use type when defining function types.

Union types

Union types can only be achieved with the type keyword:

type Fruit = 'apple' | 'pear' | 'orange';
type Vegetable = 'broccoli' | 'carrot' | 'lettuce';

// 'apple' | 'pear' | 'orange' | 'broccoli' | 'carrot' | 'lettuce';
type HealthyFoods = Fruit | Vegetable;

When defining union types, use the type keyword

Object types

An object in javascript is a key/value map, and an "object type" is typescript's way of typing those key/value maps. Both interface and type can be used when providing types for an object as the original question makes clear. So when do you use type vs interface for object types?

Intersection vs Inheritance

With types and composition, I can do something like this:

type NumLogger = { 
  log: (val: number) => void;
}
type StrAndNumLogger = NumLogger & { 
  log: (val: string) => void;
}

const logger: StrAndNumLogger = {
  log: (val: string | number) => console.log(val)
}

logger.log(1)
logger.log('hi')

Typescript is totally happy. What about if I tried that with interfaces:

interface NumLogger { 
    log: (val: number) => void;
}
interface StrAndNumLogger extends NumLogger { 
    log: (val: string) => void; 
};

The declaration of StrAndNumLogger gives me an error:

With interfaces, the subtypes have to exactly match the types declared in the super type, otherwise TS will throw an error like the one above.

When trying to overload functions in object types, you'll be better off using the type keyword.

Declaration Merging

The key aspect to interfaces in typescript that distinguish them from types is that they can be extended with new functionality after they've already been declared. A common use case for this feature occurs when you want to extend the types that are exported from a node module. For example, @types/jest exports types that can be used when working with the jest library. However, jest also allows for extending the main jest type with new functions. For example, I can add a custom test like this:

jest.timedTest = async (testName, wrappedTest, timeout) =>
  test(
    testName,
    async () => {
      const start = Date.now();
      await wrappedTest(mockTrack);
      const end = Date.now();

      console.log(`elapsed time in ms: ${end - start}`);
    },
    timeout
  );

And then I can use it like this:

test.timedTest('this is my custom test', () => {
  expect(true).toBe(true);
});

And now the time elapsed for that test will be printed to the console once the test is complete. Great! There's only one problem - typescript has no clue that i've added a timedTest function, so it'll throw an error in the editor (the code will run fine, but TS will be angry).

To resolve this, I need to tell TS that there's a new type on top of the existing types that are already available from jest. To do that, I can do this:

declare namespace jest {
  interface It {
    timedTest: (name: string, fn: (mockTrack: Mock) => any, timeout?: number) => void;
  }
}

Because of how interfaces work, this type declaration will be merged with the type declarations exported from @types/jest. So I didn't just re-declare jest.It; I extended jest.It with a new function so that TS is now aware of my custom test function.

This type of thing is not possible with the type keyword. If @types/jest had declared their types with the type keyword, I wouldn't have been able to extend those types with my own custom types, and therefore there would have been no good way to make TS happy about my new function. This process that is unique to the interface keyword is called declaration merging.

Declaration merging is also possible to do locally like this:

interface Person {
  name: string;
}

interface Person {
  age: number;
}

// no error
const person: Person = {
  name: 'Mark',
  age: 25
};

If I did the exact same thing above with the type keyword, I would have gotten an error since types cannot be re-declared/merged. In the real world, javascript objects are much like this interface example; they can be dynamically updated with new fields at runtime.

Because interface declarations can be merged, interfaces more accurately represent the dynamic nature of javascript objects than types do, and they should be preferred for that reason.

Mapped object types

With the type keyword, I can take advantage of mapped types like this:

type Fruit = 'apple' | 'orange' | 'banana';

type FruitCount = {
  [key in Fruit]: number;
}

const fruits: FruitCount = {
  apple: 2,
  orange: 3,
  banana: 4
};

This cannot be done with interfaces:

type Fruit = 'apple' | 'orange' | 'banana';

// ERROR: 
interface FruitCount {
  [key in Fruit]: number;
}

When needing to take advantage of mapped types, use the type keyword

Use PHP to create, edit and delete crontab jobs?

Its simple You can you curl to do so, make sure curl installed on server :

for triggering every minute : * * * * * curl --request POST 'https://glassdoor.com/admin/sendBdayNotification'

        • *

    minute hour day month week

Let say you want to send this notification 2:15 PM everyday You may change POST/GET based on your API:

15 14 * * * curl --request POST 'url of ur API'

What's the "Content-Length" field in HTTP header?

From this page

The most common use of POST, by far, is to submit HTML form data to CGI scripts. In this case, the Content-Type: header is usually application/x-www-form-urlencoded, and the Content-Length: header gives the length of the URL-encoded form data (here's a note on URL-encoding). The CGI script receives the message body through STDIN, and decodes it. Here's a typical form submission, using POST:

POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Perform the following steps:

  1. Start the Registry Editor by typing regedit in the Run window.
  2. Select the following key in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
  3. In the Security menu, click Permissions.
  4. Grant Full Permission to the account which is being used for making connections.
  5. Quit the Registry Editor.

Regular Expression to match valid dates

Regex was not meant to validate number ranges(this number must be from 1 to 5 when the number preceding it happens to be a 2 and the number preceding that happens to be below 6). Just look for the pattern of placement of numbers in regex. If you need to validate is qualities of a date, put it in a date object js/c#/vb, and interogate the numbers there.

How to Convert date into MM/DD/YY format in C#

Look into using the ToString() method with a specified format.

How to delete shared preferences data from App in Android

new File(context.getFilesDir(), fileName).delete();

I can delete file in shared preferences with it

Deleting an SVN branch

Sure: svn rm the unwanted folder, and commit.

To avoid this situation in the future, I would follow the recommended layout for SVN projects:

  • Put your code in the /someproject/trunk folder (or just /trunk if you want to put only one project in the repository)
  • Created branches as /someproject/branches/somebranch
  • Put tags under /someproject/tags

Now when you check out a working copy, be sure to check out only trunk or some individual branch. Don't check everything out in one huge working copy containing all branches.1

1Unless you know what you're doing, in which case you know how to create shallow working copies.

Accessing post variables using Java Servlets

For getting all post parameters there is Map which contains request param name as key and param value as key.

Map params = servReq.getParameterMap();

And to get parameters with known name normal

String userId=servReq.getParameter("user_id");

How to bind RadioButtons to an enum?

For the EnumToBooleanConverter answer: Instead of returning DependencyProperty.UnsetValue consider returning Binding.DoNothing for the case where the radio button IsChecked value becomes false. The former indicates a problem (and might show the user a red rectangle or similar validation indicators) while the latter just indicates that nothing should be done, which is what is wanted in that case.

http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.convertback.aspx http://msdn.microsoft.com/en-us/library/system.windows.data.binding.donothing.aspx

Rotating a Div Element in jQuery

I doubt you can rotate an element using DOM/CSS. Your best bet would be to render to a canvas and rotate that (not sure on the specifics).

HTML embedded PDF iframe

If the browser has a pdf plugin installed it executes the object, if not it uses Google's PDF Viewer to display it as plain HTML:

<object data="your_url_to_pdf" type="application/pdf">
    <iframe src="https://docs.google.com/viewer?url=your_url_to_pdf&embedded=true"></iframe>
</object>

What is the significance of #pragma marks? Why do we need #pragma marks?

In simple word we can say that #pragma mark - is used for categorizing methods, so you can find your methods easily. It is very useful for long projects.

How to add an extra column to a NumPy array

A bit late to the party, but nobody posted this answer yet, so for the sake of completeness: you can do this with list comprehensions, on a plain Python array:

source = a.tolist()
result = [row + [0] for row in source]
b = np.array(result)

Android Shared preferences for creating one time activity (example)

I just found all the above examples just too confusing, so I wrote my own. Code fragments are fine if you know what you're doing, but what about people like me who don't?

Want a cut-n-paste solution instead? Well here it is!

Create a new java file and call it Keystore. Then paste in this code:

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

public class Keystore { //Did you remember to vote up my example?
    private static Keystore store;
    private SharedPreferences SP;
    private static String filename="Keys";

private Keystore(Context context) {
    SP = context.getApplicationContext().getSharedPreferences(filename,0);
}

public static Keystore getInstance(Context context) {
    if (store == null) {
        Log.v("Keystore","NEW STORE");
        store = new Keystore(context);
    }
    return store;
}

public void put(String key, String value) {//Log.v("Keystore","PUT "+key+" "+value);
    Editor editor = SP.edit();
    editor.putString(key, value);
    editor.commit(); // Stop everything and do an immediate save!
    // editor.apply();//Keep going and save when you are not busy - Available only in APIs 9 and above.  This is the preferred way of saving.
}

public String get(String key) {//Log.v("Keystore","GET from "+key);
    return SP.getString(key, null);

}

public int getInt(String key) {//Log.v("Keystore","GET INT from "+key);
    return SP.getInt(key, 0);
}

public void putInt(String key, int num) {//Log.v("Keystore","PUT INT "+key+" "+String.valueOf(num));
    Editor editor = SP.edit();

    editor.putInt(key, num);
    editor.commit();
}


public void clear(){ // Delete all shared preferences
    Editor editor = SP.edit();

    editor.clear();
    editor.commit();
}

public void remove(){ // Delete only the shared preference that you want
    Editor editor = SP.edit();

    editor.remove(filename);
    editor.commit();
}
}

Now save that file and forget about it. You're done with it. Now go back into your activity and use it like this:

public class YourClass extends Activity{

private Keystore store;//Holds our key pairs

public YourSub(Context context){
    store = Keystore.getInstance(context);//Creates or Gets our key pairs.  You MUST have access to current context!

    int= store.getInt("key name to get int value");
    string = store.get("key name to get string value");

    store.putInt("key name to store int value",int_var);
    store.put("key name to store string value",string_var);
    }
}

Throwing exceptions in a PHP Try Catch block

throw $e->getMessage();

You try to throw a string

As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data

How to serialize an Object into a list of URL query parameters?

Since I made such a big deal about a recursive function, here is my own version.

function objectParametize(obj, delimeter, q) {
    var str = new Array();
    if (!delimeter) delimeter = '&';
    for (var key in obj) {
        switch (typeof obj[key]) {
            case 'string':
            case 'number':
                str[str.length] = key + '=' + obj[key];
            break;
            case 'object':
                str[str.length] = objectParametize(obj[key], delimeter);
        }
    }
    return (q === true ? '?' : '') + str.join(delimeter);
}

http://jsfiddle.net/userdude/Kk3Lz/2/

NSURLErrorDomain error codes description

I was unable to find name of an error for given code when developing in Swift. For that reason I paste minus codes for NSURLErrorDomain taken from NSURLError.h

/*!
    @enum NSURL-related Error Codes
    @abstract Constants used by NSError to indicate errors in the NSURL domain
*/
NS_ENUM(NSInteger)
{
    NSURLErrorUnknown =             -1,
    NSURLErrorCancelled =           -999,
    NSURLErrorBadURL =              -1000,
    NSURLErrorTimedOut =            -1001,
    NSURLErrorUnsupportedURL =          -1002,
    NSURLErrorCannotFindHost =          -1003,
    NSURLErrorCannotConnectToHost =         -1004,
    NSURLErrorNetworkConnectionLost =       -1005,
    NSURLErrorDNSLookupFailed =         -1006,
    NSURLErrorHTTPTooManyRedirects =        -1007,
    NSURLErrorResourceUnavailable =         -1008,
    NSURLErrorNotConnectedToInternet =      -1009,
    NSURLErrorRedirectToNonExistentLocation =   -1010,
    NSURLErrorBadServerResponse =       -1011,
    NSURLErrorUserCancelledAuthentication =     -1012,
    NSURLErrorUserAuthenticationRequired =  -1013,
    NSURLErrorZeroByteResource =        -1014,
    NSURLErrorCannotDecodeRawData =             -1015,
    NSURLErrorCannotDecodeContentData =         -1016,
    NSURLErrorCannotParseResponse =             -1017,
    NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
    NSURLErrorFileDoesNotExist =        -1100,
    NSURLErrorFileIsDirectory =         -1101,
    NSURLErrorNoPermissionsToReadFile =     -1102,
    NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103,

    // SSL errors
    NSURLErrorSecureConnectionFailed =      -1200,
    NSURLErrorServerCertificateHasBadDate =     -1201,
    NSURLErrorServerCertificateUntrusted =  -1202,
    NSURLErrorServerCertificateHasUnknownRoot = -1203,
    NSURLErrorServerCertificateNotYetValid =    -1204,
    NSURLErrorClientCertificateRejected =   -1205,
    NSURLErrorClientCertificateRequired =   -1206,
    NSURLErrorCannotLoadFromNetwork =       -2000,

    // Download and file I/O errors
    NSURLErrorCannotCreateFile =        -3000,
    NSURLErrorCannotOpenFile =          -3001,
    NSURLErrorCannotCloseFile =         -3002,
    NSURLErrorCannotWriteToFile =       -3003,
    NSURLErrorCannotRemoveFile =        -3004,
    NSURLErrorCannotMoveFile =          -3005,
    NSURLErrorDownloadDecodingFailedMidStream = -3006,
    NSURLErrorDownloadDecodingFailedToComplete =-3007,

    NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018,
    NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019,
    NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020,
    NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021,

    NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
    NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
    NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
};

Reading a JSP variable from JavaScript

Assuming you are talking about JavaScript in an HTML document.

You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.

You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.

The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of http://json.org/ ) and then have the JSP output:

<script type="text/javascript">
    var myObject = <%= the string output by the JSON library %>;
</script>

This will give you an object that you can access like:

myObject.someProperty

in the JS.