Programs & Examples On #Fdt

FDT is an Eclipse development toolkit for interactive developers. FDT can be used to target multiple platforms such as Flash and HTML5 / JavaScript / PHP via Haxe.

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

How to convert image into byte array and byte array to base64 String in android?

Try this simple solution to convert file to base64 string

String base64String = imageFileToByte(file);

public String imageFileToByte(File file){

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

Well, you should also try adding the Javascript code into a function, then calling the function after document body has loaded..it worked for me :)

Python base64 data decode

Note Slipstream's response, that base64.b64encode and base64.b64decode need bytes-like object, not string.

>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python3.6/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

Create table with jQuery - append

Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu"> on any page to reproduce the HTML.

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>HTML Masterpage</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

        <script type="text/javascript">
            function nav() {
                var menuHTML= '<ul><li><a href="#">link 1</a></li></ul><ul><li><a href="#">link 2</a></li></ul>';
                $('#menu').append(menuHTML);
            }
        </script>

        <style type="text/css">
        </style>
    </head>
    <body onload="nav()">
        <div id="menu"></div>
    </body>
    </html>

Commenting multiple lines in DOS batch file

try this:

   @echo off 2>Nul 3>Nul 4>Nul

   ben ali
   mubarak
   gadeffi
   ..next ?

   echo hello Tunisia

  pause

How to give a delay in loop execution using Qt

As an update of @Live's answer, for Qt = 5.2 there is no more need to subclass QThread, as now the sleep functions are public:

Static Public Members

  • QThread * currentThread()
  • Qt::HANDLE currentThreadId()
  • int idealThreadCount()
  • void msleep(unsigned long msecs)
  • void sleep(unsigned long secs)
  • void usleep(unsigned long usecs)
  • void yieldCurrentThread()

cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members

Correct way to populate an Array with a Range in Ruby

Sounds like you're doing this:

0..10.to_a

The warning is from Fixnum#to_a, not from Range#to_a. Try this instead:

(0..10).to_a

Disable scrolling in an iPhone web application?

The page has to be launched from the Home screen for the meta tag to work.

How to link to apps on the app store

This is simple and short way to redirect/link other existing application on app store.

 NSString *customURL = @"http://itunes.apple.com/app/id951386316";

 if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
 {
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
 } 

Can an ASP.NET MVC controller return an Image?

Use the base controllers File method.

public ActionResult Image(string id)
{
    var dir = Server.MapPath("/Images");
    var path = Path.Combine(dir, id + ".jpg"); //validate the path for security or use other means to generate the path.
    return base.File(path, "image/jpeg");
}

As a note, this seems to be fairly efficient. I did a test where I requested the image through the controller (http://localhost/MyController/Image/MyImage) and through the direct URL (http://localhost/Images/MyImage.jpg) and the results were:

  • MVC: 7.6 milliseconds per photo
  • Direct: 6.7 milliseconds per photo

Note: this is the average time of a request. The average was calculated by making thousands of requests on the local machine, so the totals should not include network latency or bandwidth issues.

Why I can't access remote Jupyter Notebook server?

I got the same problem but none of workarounds above work for me. But if I setup a docker version jupyter notebook, with the same configuration, it works out for me.

For my stituation, it might be iptables rule issues. Sometimes you may just using ufw to allow all route to your server. But mine just iptables -F to clear all rule. Then check iptables -L -n to see if its works.

Problem fixed.

Java, How to specify absolute value and square roots

import java.util.Scanner;
class my{
public static void main(String args[])
{
    Scanner x=new Scanner(System.in);
    double a,b,c=0,d;
    d=1;
    d=d/10;
    int e,z=0;
    System.out.print("Enter no:");
    a=x.nextInt();

    for(b=1;b<=a/2;b++)
    {
        if(b*b==a)
        {
            c=b;
            break;
        }
        else
        {
            if(b*b>a)
            break;
        }
    } 
    b--;
    if(c==0)
    {
       for(e=1;e<=15;e++)
        {
            while(b*b<=a && z==0)
            {
                if(b*b==a){c=b;z=1;}
                else
                {
                    b=b+d;          //*d==0.1 first time*//
                    if(b*b>=a){z=1;b=b-d;}
                }
            }
            d=d/10;
            z=0;
        }
        c=b;
    }

        System.out.println("Squre root="+c);





}    
}    

Only read selected columns

You could also use JDBC to achieve this. Let's create a sample csv file.

write.table(x=mtcars, file="mtcars.csv", sep=",", row.names=F, col.names=T) # create example csv file

Download and save the the CSV JDBC driver from this link: http://sourceforge.net/projects/csvjdbc/files/latest/download

> library(RJDBC)

> path.to.jdbc.driver <- "jdbc//csvjdbc-1.0-18.jar"
> drv <- JDBC("org.relique.jdbc.csv.CsvDriver", path.to.jdbc.driver)
> conn <- dbConnect(drv, sprintf("jdbc:relique:csv:%s", getwd()))

> head(dbGetQuery(conn, "select * from mtcars"), 3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1   21   6  160 110  3.9  2.62 16.46  0  1    4    4
2   21   6  160 110  3.9 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85  2.32 18.61  1  1    4    1

> head(dbGetQuery(conn, "select mpg, gear from mtcars"), 3)
   MPG GEAR
1   21    4
2   21    4
3 22.8    4

CSS flexbox not working in IE10

As Ennui mentioned, IE 10 supports the -ms prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:

  • You should have display: -ms-flexbox instead of display: -ms-flex
  • I think you should specify all 3 flex values, like flex: 0 1 auto to avoid ambiguity

So the final updated code is...

.flexbox form {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flexbox;
    display: -o-flex;
    display: flex;

    /* Direction defaults to 'row', so not really necessary to specify */
    -webkit-flex-direction: row;
    -moz-flex-direction: row;
    -ms-flex-direction: row;
    -o-flex-direction: row;
    flex-direction: row;
}

.flexbox form input[type=submit] {
    width: 31px;
}

.flexbox form input[type=text] {
    width: auto;

    /* Flex should have 3 values which is shorthand for 
       <flex-grow> <flex-shrink> <flex-basis> */
    -webkit-flex: 1 1 auto;
    -moz-flex: 1 1 auto;
    -ms-flex: 1 1 auto;
    -o-flex: 1 1 auto;
    flex: 1 1 auto;

    /* I don't think you need 'display: flex' on child elements * /
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: -o-flex;
    display: flex;
    /**/
}

Laravel orderBy on a relationship

Using sortBy... could help.

$users = User::all()->with('rated')->get()->sortByDesc('rated.rating');

OraOLEDB.Oracle provider is not registered on the local machine

My team would stumble upon this issue every now and then in random machines that we would try to install our platform in (we use oracle drivers 12c ver 12.2.0.4 but we came across this bug with other versions as well)

After quite a bit of experimentation we realized what was wrong:

Said machines would have apps that were using the machine-wide oracle drivers silently locking them and preventing the oracle driver-installer from working its magic when would attempt to upgrade/reinstall said oracle-drivers. The sneakiest "app" would be websites running in IIS and the like because these apps essentially auto-start on reboot. To counter this we do the following:

  1. Disable IIS from starting automagically on restart. Do the same for any other apps/services that auto-start themselves on reboot.
  2. Uninstall any previous Oracle driver and double-check that there are no traces left behind in registry or folders.
  3. Reboot the machine
  4. (Re)Install the Oracle drivers and re-enable IIS and other auto-start apps.
  5. Reboot the machine <- This is vital. Oracle's OLE DB drivers won't work unless you reboot the machine.

If this doesn't work then rinse repeat until the OLE DB drivers work. Hope this helps someone out there struggling to figure out what's going on.

Can I convert long to int?

Wouldn't

(int) Math.Min(Int32.MaxValue, longValue)

be the correct way, mathematically speaking?

Normalize data in pandas

You can use apply for this, and it's a bit neater:

import numpy as np
import pandas as pd

np.random.seed(1)

df = pd.DataFrame(np.random.randn(4,4)* 4 + 3)

          0         1         2         3
0  9.497381  0.552974  0.887313 -1.291874
1  6.461631 -6.206155  9.979247 -0.044828
2  4.276156  2.002518  8.848432 -5.240563
3  1.710331  1.463783  7.535078 -1.399565

df.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

          0         1         2         3
0  0.515087  0.133967 -0.651699  0.135175
1  0.125241 -0.689446  0.348301  0.375188
2 -0.155414  0.310554  0.223925 -0.624812
3 -0.484913  0.244924  0.079473  0.114448

Also, it works nicely with groupby, if you select the relevant columns:

df['grp'] = ['A', 'A', 'B', 'B']

          0         1         2         3 grp
0  9.497381  0.552974  0.887313 -1.291874   A
1  6.461631 -6.206155  9.979247 -0.044828   A
2  4.276156  2.002518  8.848432 -5.240563   B
3  1.710331  1.463783  7.535078 -1.399565   B


df.groupby(['grp'])[[0,1,2,3]].apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

     0    1    2    3
0  0.5  0.5 -0.5 -0.5
1 -0.5 -0.5  0.5  0.5
2  0.5  0.5  0.5 -0.5
3 -0.5 -0.5 -0.5  0.5

Thymeleaf using path variables to th:href

Your code looks syntactically correct, but I think your property doesn't exist to create the URL.

I just tested it, and it works fine for me.

Try using category.idCategory instead of category.id, for example…

  <tr th:each="category : ${categories}">
    <td th:text="${category.idCategory}"></td>
    <td th:text="${category.name}"></td>
    <td>
      <a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>
    </td>
  </tr>

Set focus to field in dynamically loaded DIV

This runs on page load.

<script type="text/javascript">
    $(function () {
        $("#header").focus();
    });
</script>

Get property value from string using reflection

Here is my solution. It works also with COM objects and allows to access collection/array items from COM objects.

public static object GetPropValue(this object obj, string name)
{
    foreach (string part in name.Split('.'))
    {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        if (type.Name == "__ComObject")
        {
            if (part.Contains('['))
            {
                string partWithoundIndex = part;
                int index = ParseIndexFromPropertyName(ref partWithoundIndex);
                obj = Versioned.CallByName(obj, partWithoundIndex, CallType.Get, index);
            }
            else
            {
                obj = Versioned.CallByName(obj, part, CallType.Get);
            }
        }
        else
        {
            PropertyInfo info = type.GetProperty(part);
            if (info == null) { return null; }
            obj = info.GetValue(obj, null);
        }
    }
    return obj;
}

private static int ParseIndexFromPropertyName(ref string name)
{
    int index = -1;
    int s = name.IndexOf('[') + 1;
    int e = name.IndexOf(']');
    if (e < s)
    {
        throw new ArgumentException();
    }
    string tmp = name.Substring(s, e - s);
    index = Convert.ToInt32(tmp);
    name = name.Substring(0, s - 1);
    return index;
}

View list of all JavaScript variables in Google Chrome Console

Type: this in the console,

to get the window object I think(?), I think it's basically the same as typing window in the console.

It works at least in Firefox & chrome.

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

try giving AppPool ID or Network Services whichever applicable access HKLM\SYSTEM\CurrentControlSet\services\eventlog\security also. I was getting the same error .. this worked for me. See the error is also saying that the inaccessible logs are Security Logs.

I also gave permission in eventlog\application .

I gave full access everywhere.

How to delete duplicates on a MySQL table?

Following remove duplicates for all SID-s, not only single one.

With temp table

CREATE TABLE table_temp AS
SELECT * FROM table GROUP BY title, SID;

DROP TABLE table;
RENAME TABLE table_temp TO table;

Since temp_table is freshly created it has no indexes. You'll need to recreate them after removing duplicates. You can check what indexes you have in the table with SHOW INDEXES IN table

Without temp table:

DELETE FROM `table` WHERE id IN (
  SELECT all_duplicates.id FROM (
    SELECT id FROM `table` WHERE (`title`, `SID`) IN (
      SELECT `title`, `SID` FROM `table` GROUP BY `title`, `SID` having count(*) > 1
    )
  ) AS all_duplicates 
  LEFT JOIN (
    SELECT id FROM `table` GROUP BY `title`, `SID` having count(*) > 1
  ) AS grouped_duplicates 
  ON all_duplicates.id = grouped_duplicates.id 
  WHERE grouped_duplicates.id IS NULL
)

How can I use nohup to run process as a background process in linux?

You can write a script and then use nohup ./yourscript & to execute

For example:

vi yourscript

put

#!/bin/bash
script here

you may also need to change permission to run script on server

chmod u+rwx yourscript

finally

nohup ./yourscript &

Simulate a click on 'a' element using javascript/jquery

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

Installing mcrypt extension for PHP on OSX Mountain Lion

I tend to use Homebrew on Mac. It will install and configure all the stuff for you.
http://mxcl.github.com/homebrew/

Then you should be able to install it with brew install mcrypt php53-mcrypt and it'll Just Work (tm).

You can replace the 53 with whatever version of PHP you're using, such as php56-mcrypt or php70-mcrypt. If you're not sure, use brew search php.

Do also remember that if you are using the built in Mac PHP it's installed into /usr/bin you can see which php you are using with which php at the terminal and it'll return the path.

Creating a random string with A-Z and 0-9 in Java

Three steps to implement your function:

Step#1 You can specify a string, including the chars A-Z and 0-9.

Like.

 String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

Step#2 Then if you would like to generate a random char from this candidate string. You can use

 candidateChars.charAt(random.nextInt(candidateChars.length()));

Step#3 At last, specify the length of random string to be generated (in your description, it is 17). Writer a for-loop and append the random chars generated in step#2 to StringBuilder object.

Based on this, here is an example public class RandomTest {

public static void main(String[] args) {

    System.out.println(generateRandomChars(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 17));
}

/**
 * 
 * @param candidateChars
 *            the candidate chars
 * @param length
 *            the number of random chars to be generated
 * 
 * @return
 */
public static String generateRandomChars(String candidateChars, int length) {
    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < length; i++) {
        sb.append(candidateChars.charAt(random.nextInt(candidateChars
                .length())));
    }

    return sb.toString();
}

}

Given two directory trees, how can I find out which files differ by content?

These two commands do basically the thing asked for:

diff --brief --recursive --no-dereference --new-file --no-ignore-file-name-case /dir1 /dir2 > dirdiff_1.txt

rsync --recursive --delete --links --checksum --verbose --dry-run /dir1/ /dir2/ > dirdiff_2.txt

The choice between them depends on the location of dir1 and dir2:

When the directories reside on two seperate drives, diff outperforms rsync. But when the two directories compared are on the same drive, rsync is faster. It's because diff puts an almost equal load on both directories in parallel, maximizing load on the two drives.

rsync calculates checksums in large chunks before actually comparing them. That groups the i/o operations in large chunks and leads to a more efficient processing when things take place on a single drive.

Using Case/Switch and GetType to determine the object

If I really had to switch on type of object, I'd use .ToString(). However, I would avoid it at all costs: IDictionary<Type, int> will do much better, visitor might be an overkill but otherwise it is still a perfectly fine solution.

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

You perhaps use the wrong username.

I had a similar error. Ensure you're not using uppercase while logging into server.

Example: [email protected]

If you use ->setUsername('JacekPL'), this can cause an error. Use ->setUsername('jacekpl') instead. This solved my problem.

How to change a dataframe column from String type to Double type in PySpark?

pyspark version:

  df = <source data>
  df.printSchema()

  from pyspark.sql.types import *

  # Change column type
  df_new = df.withColumn("myColumn", df["myColumn"].cast(IntegerType()))
  df_new.printSchema()
  df_new.select("myColumn").show()

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

How to get current route

import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

Rather than using a DisplayFilter you could use a very simple CaptureFilter like

port 53

See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

Updating GUI (WPF) using a different thread

there.

I am also developing a serial port testing tool using WPF, and I'd like to share some experience of mine.

I think you should refactor your source code according to MVVM design pattern.

At the beginning, I met the same problem as you met, and I solved it using this code:

new Thread(() => 
{
    while (...)
    {
        SomeTextBox.Dispatcher.BeginInvoke((Action)(() => SomeTextBox.Text = ...));
    }
}).Start();

This works, but is too ugly. I have no idea how to refactor it, until I saw this: http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial

This is a very kindly step-by-step MVVM tutorial for beginners. No shiny UI, no complex logic, only the basic of MVVM.

Eclipse: How do you change the highlight color of the currently selected method/expression?

If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.

  1. Right click on highlighted word
  2. Select 'Preferences'
  3. Go to General > Editors > Text Editors > Annotations. Now look for "PHP elements 'read' occurrences" and "PHP elements 'write' occurrences". You can select your desired colour there.

Change Highlighted text colour in Eclips with PHP

Looping through the content of a file in Bash

One way to do it is:

while read p; do
  echo "$p"
done <peptides.txt

As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do:

while IFS="" read -r p || [ -n "$p" ]
do
  printf '%s\n' "$p"
done < peptides.txt

Exceptionally, if the loop body may read from standard input, you can open the file using a different file descriptor:

while read -u 10 p; do
  ...
done 10<peptides.txt

Here, 10 is just an arbitrary number (different from 0, 1, 2).

Apply style ONLY on IE

There are severals hacks available for IE

Using conditional comments with stylesheet

<!--[if IE]>
<link rel="stylesheet" type="text/css" href="only-ie.css" />
<![endif]-->

Using conditional comments with head section css

<!--[if IE]>
<style type="text/css">
    /************ css for all IE browsers ****************/
</style>
<![endif]-->

Using conditional comments with HTML elements

<!--[if IE]> <div class="ie-only"> /*content*/ </div> <![endif]-->

Using media query

 IE10+
 @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
 selector { property:value; }
 }

 IE6,7,9,10
 @media screen and (min-width: 640px), screen\9 {
 selector { property:value; }
 }

 IE6,7
 @media screen\9 {
  selector { property:value; }
 }

 IE8
 @media \0screen {
  selector { property:value; }
 }

 IE6,7,8
 @media \0screen\,screen\9 {
  selector { property:value; }
 }

 IE9,10
 @media screen and (min-width:0\0){
  selector { property:value; }
 }

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

Make sure you format the string like this or it wont work

 $content = "BEGIN:VCALENDAR\n".
            "VERSION:2.0\n".
            "PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n".
            "BEGIN:VEVENT\n".
            "UID:".uniqid()."\n".
            "DTSTAMP:".$time."\n".
            "DTSTART:".$time."\n".
            "DTEND:".$time."\n".
            "SUMMARY:".$summary."\n".
            "END:VEVENT\n".
            "END:VCALENDAR";

SQL SELECT everything after a certain character

select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;

Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.

inline conditionals in angular.js

I'll throw mine in the mix:

https://gist.github.com/btm1/6802312

this evaluates the if statement once and adds no watch listener BUT you can add an additional attribute to the element that has the set-if called wait-for="somedata.prop" and it will wait for that data or property to be set before evaluating the if statement once. that additional attribute can be very handy if you're waiting for data from an XHR request.

angular.module('setIf',[]).directive('setIf',function () {
    return {
      transclude: 'element',
      priority: 1000,
      terminal: true,
      restrict: 'A',
      compile: function (element, attr, linker) {
        return function (scope, iterStartElement, attr) {
          if(attr.waitFor) {
            var wait = scope.$watch(attr.waitFor,function(nv,ov){
              if(nv) {
                build();
                wait();
              }
            });
          } else {
            build();
          }

          function build() {
            iterStartElement[0].doNotMove = true;
            var expression = attr.setIf;
            var value = scope.$eval(expression);
            if (value) {
              linker(scope, function (clone) {
                iterStartElement.after(clone);
                clone.removeAttr('set-if');
                clone.removeAttr('wait-for');
              });
            }
          }
        };
      }
    };
  });

Regex replace uppercase with lowercase letters

Before searching with regex like [A-Z], you should press the case sensitive button (or Alt+C) (as leemour nicely suggested to be edited in the accepted answer). Just to be clear, I'm leaving a few other examples:

  1. Capitalize words
    • Find: (\s)([a-z]) (\s also matches new lines, i.e. "venuS" => "VenuS")
    • Replace: $1\u$2
  2. Uncapitalize words
    • Find: (\s)([A-Z])
    • Replace: $1\l$2
  3. Remove camel case (e.g. cAmelCAse => camelcAse => camelcase)
    • Find: ([a-z])([A-Z])
    • Replace: $1\l$2
  4. Lowercase letters within words (e.g. LowerCASe => Lowercase)
    • Find: (\w)([A-Z]+)
    • Replace: $1\L$2
    • Alternate Replace: \L$0
  5. Uppercase letters within words (e.g. upperCASe => uPPERCASE)
    • Find: (\w)([A-Z]+)
    • Replace: $1\U$2
  6. Uppercase previous (e.g. upperCase => UPPERCase)
    • Find: (\w+)([A-Z])
    • Replace: \U$1$2
  7. Lowercase previous (e.g. LOWERCase => lowerCase)
    • Find: (\w+)([A-Z])
    • Replace: \L$1$2
  8. Uppercase the rest (e.g. upperCase => upperCASE)
    • Find: ([A-Z])(\w+)
    • Replace: $1\U$2
  9. Lowercase the rest (e.g. lOWERCASE => lOwercase)
    • Find: ([A-Z])(\w+)
    • Replace: $1\L$2
  10. Shift-right-uppercase (e.g. Case => cAse => caSe => casE)
    • Find: ([a-z\s])([A-Z])(\w)
    • Replace: $1\l$2\u$3
  11. Shift-left-uppercase (e.g. CasE => CaSe => CAse => Case)
    • Find: (\w)([A-Z])([a-z\s])
    • Replace: \u$1\l$2$3

Regarding the question (match words with at least one uppercase and one lowercase letter and make them lowercase), leemour's comment-answer is the right answer. Just to clarify, if there is only one group to replace, you can just use ?: in the inner groups (i.e. non capture groups) or avoid creating them at all:

  • Find: ((?:[a-z][A-Z]+)|(?:[A-Z]+[a-z])) OR ([a-z][A-Z]+|[A-Z]+[a-z])
  • Replace: \L$1

2016-06-23 Edit

Tyler suggested by editing this answer an alternate find expression for #4:

  • (\B)([A-Z]+)

According to the documentation, \B will look for a character that is not at the word's boundary (i.e. not at the beginning and not at the end). You can use the Replace All button and it does the exact same thing as if you had (\w)([A-Z]+) as the find expression.

However, the downside of \B is that it does not allow single replacements, perhaps due to the find's "not boundary" restriction (please do edit this if you know the exact reason).

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

This is the quickest way to solve the problem but it's not recommended because its applicable only for your local system.

Download the jar, comment your previous entry for ojdbc6, and give a new local entry like so:

Previous Entry:

<!-- OJDBC6 Dependency -->
        <!-- <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>1.0</version>
            <scope>runtime</scope>
        </dependency> -->

New Entry:

<dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/ojdbc6/ojdbc6.jar</systemPath>
        </dependency> 

How to display the string html contents into webbrowser control?

Try this:

webBrowser1.DocumentText =
    "<html><body>Please enter your name:<br/>" +
    "<input type='text' name='userName'/><br/>" +
    "<a href='http://www.microsoft.com'>continue</a>" +
    "</body></html>";

Checking if any elements in one list are in another

There are different ways. If you just want to check if one list contains any element from the other list, you can do this..

not set(list1).isdisjoint(list2)

I believe using isdisjoint is better than intersection for Python 2.6 and above.

How to show "Done" button on iPhone number pad

We can also make the "user touched somewhere else" solution even simpler if we just tell our view controller's view to end editing:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
 { 
      [super touchesBegan:touches withEvent:event];

      [self.view endEditing:YES]; //YES ignores any textfield refusal to resign
 }

... assuming that "touching elsewhere dismisses the keyboard" is desired behavior for any other editable fields on the view as well.

BACKUP LOG cannot be performed because there is no current database backup

Another cause for this is if you have the same database restored under a different name. Delete the existing one and then restoring solved it for me.

How to delete duplicate rows in SQL Server?

I like CTEs and ROW_NUMBER as the two combined allow us to see which rows are deleted (or updated), therefore just change the DELETE FROM CTE... to SELECT * FROM CTE:

WITH CTE AS(
   SELECT [col1], [col2], [col3], [col4], [col5], [col6], [col7],
       RN = ROW_NUMBER()OVER(PARTITION BY col1 ORDER BY col1)
   FROM dbo.Table1
)
DELETE FROM CTE WHERE RN > 1

DEMO (result is different; I assume that it's due to a typo on your part)

COL1    COL2    COL3    COL4    COL5    COL6    COL7
john    1        1       1       1       1       1
sally   2        2       2       2       2       2

This example determines duplicates by a single column col1 because of the PARTITION BY col1. If you want to include multiple columns simply add them to the PARTITION BY:

ROW_NUMBER()OVER(PARTITION BY Col1, Col2, ... ORDER BY OrderColumn)

CSS float right not working correctly

Here is one way of doing it.

If you HTML looks like this:

<div>Contact Details
    <button type="button" class="edit_button">My Button</button>
</div>

apply the following CSS:

div {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: gray;
    overflow: auto;
}
.edit_button {
    float: right;
    margin: 0 10px 10px 0; /* for demo only */
}

The trick is to apply overflow: auto to the div, which starts a new block formatting context. The result is that the floated button is enclosed within the block area defined by the div tag.

You can then add margins to the button if needed to adjust your styling.

In the original HTML and CSS, the floated button was out of the content flow so the border of the div would be positioned with respect to the in-flow text, which does not include any floated elements.

See demo at: http://jsfiddle.net/audetwebdesign/AGavv/

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

it turns out that I got this error because my requested module is not bundled in the minification prosses due to path misspelling

so make sure that your module exists in minified js file (do search for a word within it to be sure)

What is the default lifetime of a session?

it depends on your php settings...
use phpinfo() and take a look at the session chapter. There are values like session.gc_maxlifetime and session.cache_expire and session.cookie_lifetime which affects the sessions lifetime

EDIT: it's like Martin write before

Is it possible to CONTINUE a loop from an exception?

Notice you can use WHEN exception THEN NULL the same way as you would use WHEN exception THEN continue. Example:

    DECLARE
        extension_already_exists  EXCEPTION;
        PRAGMA EXCEPTION_INIT(extension_already_exists, -20007);
        l_hidden_col_name  varchar2(32);
    BEGIN
        FOR t IN (  SELECT table_name, cast(extension as varchar2(200)) ext
                    FROM all_stat_extensions
                    WHERE owner='{{ prev_schema }}'
                      and droppable='YES'
                    ORDER BY 1
                 )
        LOOP
            BEGIN
                l_hidden_col_name := dbms_stats.create_extended_stats('{{ schema }}', t.table_name, t.ext);
            EXCEPTION
                WHEN extension_already_exists THEN NULL;   -- ignore exception and go to next loop iteration
            END;
        END LOOP;
    END;

How to create <input type=“text”/> dynamically

You could use createElement() method for creating that textbox

how to prevent adding duplicate keys to a javascript array

Generally speaking, this is better accomplished with an object instead since JavaScript doesn't really have associative arrays:

var foo = { bar: 0 };

Then use in to check for a key:

if ( !( 'bar' in foo ) ) {
    foo['bar'] = 42;
}

As was rightly pointed out in the comments below, this method is useful only when your keys will be strings, or items that can be represented as strings (such as numbers).

phpexcel to download

FOR XLSX USE

SET IN $xlsName name from XLSX with extension. Example: $xlsName = 'teste.xlsx';

$objPHPExcel = new PHPExcel();

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');

FOR XLS USE

SET IN $xlsName name from XLS with extension. Example: $xlsName = 'teste.xls';

$objPHPExcel = new PHPExcel();

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');

Getting a list of all subdirectories in the current directory

If you need a recursive solution that will find all the subdirectories in the subdirectories, use walk as proposed before.

If you only need the current directory's child directories, combine os.listdir with os.path.isdir

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

I hope (not exactly verified) that newer java brought nio package and Path. Hopefully it have it fixed: String s="C:\\some\\ile.txt"; System.out.println(new File(s).toPath().toUri());

Find an element in a list of tuples

>>> [i for i in a if 1 in i]

[(1, 2), (1, 4)]

Closing Bootstrap modal onclick

Close the modal with universal $().hide() method:

$('#product-options').hide();

Can Twitter Bootstrap alerts fade in as well as out?

I don't agree with the way that Bootstrap uses fade in (as seen in their documentation - http://v4-alpha.getbootstrap.com/components/alerts/), and my suggestion is to avoid the class names fade and in, and to avoid that pattern in general (which is currently seen in the top-rated answer to this question).

(1) The semantics are wrong - transitions are temporary, but the class names live on. So why should we name our classes fade and fade in? It should be faded and faded-in, so that when developers read the markup, it's clear that those elements were faded or faded-in. The Bootstrap team has already done away with hide for hidden, why is fade any different?

(2) Using 2 classes fade and in for a single transition pollutes the class space. And, it's not clear that fade and in are associated with one another. The in class looks like a completely independent class, like alert and alert-success.

The best solution is to use faded when the element has been faded out, and to replace that class with faded-in when the element has been faded in.

Alert Faded

So to answer the question. I think the alert markup, style, and logic should be written in the following manner. Note: Feel free to replace the jQuery logic, if you're using vanilla javascript.

HTML

<div id="saveAlert" class="alert alert-success">
  <a class="close" href="#">×</a>
  <p><strong>Well done!</strong> You successfully read this alert message.</p>
</div>

CSS

.faded {
  opacity: 0;
  transition: opacity 1s;
}

JQuery

$('#saveAlert .close').on('click', function () {

  $("#saveAlert")
    .addClass('faded');

});

How to include static library in makefile

use

LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

Passing data from controller to view in Laravel

The best and easy way to pass single or multiple variables to view from controller is to use compact() method.

For passing single variable to view,

return view("user/regprofile",compact('students'));

For passing multiple variable to view,

return view("user/regprofile",compact('students','teachers','others'));

And in view, you can easily loop through the variable,

@foreach($students as $student)
   {{$student}}
@endforeach

Fatal error: Call to undefined function imap_open() in PHP

I had the same issue. After changing a semicolon in the php.ini file I solved my problem. Let's see how can you solve it?

First, open php.ini file. xampp/php/php.ini

Search extension=imap

remove semicolon before extension and save this file.

Code before remove semicolon ;extension=imap

Code after remove semicolon extension=imap

Finally, open the XAMPP Control panel and restart Apache.

What is the difference between LATERAL and a subquery in PostgreSQL?

What is a LATERAL join?

The feature was introduced with PostgreSQL 9.3.
Quoting the manual:

Subqueries appearing in FROM can be preceded by the key word LATERAL. This allows them to reference columns provided by preceding FROM items. (Without LATERAL, each subquery is evaluated independently and so cannot cross-reference any other FROM item.)

Table functions appearing in FROM can also be preceded by the key word LATERAL, but for functions the key word is optional; the function's arguments can contain references to columns provided by preceding FROM items in any case.

Basic code examples are given there.

More like a correlated subquery

A LATERAL join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a LATERAL join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. (The query planner has ways to optimize performance for either, though.)
Related answer with code examples for both side by side, solving the same problem:

For returning more than one column, a LATERAL join is typically simpler, cleaner and faster.
Also, remember that the equivalent of a correlated subquery is LEFT JOIN LATERAL ... ON true:

Things a subquery can't do

There are things that a LATERAL join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows - with the exception of bare function calls (which multiply result rows if they return multiple rows). But even certain set-returning functions are only allowed in the FROM clause. Like unnest() with multiple parameters in Postgres 9.4 or later. The manual:

This is only allowed in the FROM clause;

So this works, but cannot (easily) be replaced with a subquery:

CREATE TABLE tbl (a1 int[], a2 int[]);
SELECT * FROM tbl, unnest(a1, a2) u(elem1, elem2);  -- implicit LATERAL

The comma (,) in the FROM clause is short notation for CROSS JOIN.
LATERAL is assumed automatically for table functions.
About the special case of UNNEST( array_expression [, ... ] ):

Set-returning functions in the SELECT list

You can also use set-returning functions like unnest() in the SELECT list directly. This used to exhibit surprising behavior with more than one such function in the same SELECT list up to Postgres 9.6. But it has finally been sanitized with Postgres 10 and is a valid alternative now (even if not standard SQL). See:

Building on above example:

SELECT *, unnest(a1) AS elem1, unnest(a2) AS elem2
FROM   tbl;

Comparison:

dbfiddle for pg 9.6 here
dbfiddle for pg 10 here

Clarify misinformation

The manual:

For the INNER and OUTER join types, a join condition must be specified, namely exactly one of NATURAL, ON join_condition, or USING (join_column [, ...]). See below for the meaning.
For CROSS JOIN, none of these clauses can appear.

So these two queries are valid (even if not particularly useful):

SELECT *
FROM   tbl t
LEFT   JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t ON TRUE;

SELECT *
FROM   tbl t, LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;

While this one is not:

SELECT *
FROM   tbl t
LEFT   JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;

That's why Andomar's code example is correct (the CROSS JOIN does not require a join condition) and Attila's is was not.

What is the C# equivalent of NaN or IsNumeric?

Maybe this is a C# 3 feature, but you could use double.NaN.

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I had the same problem. I fixed it by adding an empty __init__.py file to my tests directory.

Reading a string with spaces with sscanf

You want the %c conversion specifier, which just reads a sequence of characters without special handling for whitespace.

Note that you need to fill the buffer with zeroes first, because the %c specifier doesn't write a nul-terminator. You also need to specify the number of characters to read (otherwise it defaults to only 1):

memset(buffer, 0, 200);
sscanf("19 cool kid", "%d %199c", &age, buffer);

FirebaseInstanceIdService is deprecated

Kotlin allows for even simpler code than what's shown in other answers.

To get the new token whenever it's refreshed:

class MyFirebaseMessagingService: FirebaseMessagingService() {

    override fun onNewToken(token: String?) {
        Log.d("FMS_TOKEN", token)
    }
    ...
}

To get the token from anywhere at runtime:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener {
    Log.d("FMS_TOKEN", it.token)
}

Running PHP script from the command line

On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.

If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.

You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.

Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.

RestSharp JSON Parameter Posting

You don't have to serialize the body yourself. Just do

request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new { A = "foo", B = "bar" }); // Anonymous type object is converted to Json body

If you just want POST params instead (which would still map to your model and is a lot more efficient since there's no serialization to JSON) do this:

request.AddParameter("A", "foo");
request.AddParameter("B", "bar");

How to select the last column of dataframe

df.T.iloc[-1]

df.T.tail(1)

pd.Series(df.values[:, -1], name=df.columns[-1])

adding multiple event listeners to one element

I just made this function (intentionally minified):

((i,e,f)=>e.forEach(o=>i.addEventListener(o,f)))(element, events, handler)

Usage:

((i,e,f)=>e.forEach(o=>i.addEventListener(o,f)))(element, ['click', 'touchstart'], (event) => {
    // function body
});

The difference compared to other approaches is that the handling function is defined only once and then passed to every addEventListener.

EDIT:

Adding a non-minified version to make it more comprehensible. The minified version was meant just to be copy-pasted and used.

((element, event_names, handler) => {

    event_names.forEach( (event_name) => {
        element.addEventListener(event_name, handler)
    })

})(element, ['click', 'touchstart'], (event) => {

    // function body

});

What is App.config in C#.NET? How to use it?

You can access keys in the App.Config using:

ConfigurationSettings.AppSettings["KeyName"]

Take alook at this Thread

"Input string was not in a correct format."

You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.

Pivoting rows into columns dynamically in Oracle

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from: http://orafaq.com/wiki/PIVOT

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

How to make a <div> always full screen?

This always works for me:

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
        html, body {
            height: 100%;
            margin: 0;
        }

        #wrapper {
            min-height: 100%; 
        }
    </style>
    <!--[if lte IE 6]>
    <style type="text/css">
        #container {
            height: 100%;
        }
    </style>
    <![endif]-->
</head>

<body>
    <div id="wrapper">some content</div>
</body>

This is probably the simplest solution to this problem. Only need to set four CSS attributes (although one of them is only to make IE happy).

CMAKE_MAKE_PROGRAM not found

I’ve just solved the same problem. I had MinGW with GCC and G++ installed but not make. This command helped me:

mingw-get.exe install mingw32-make

After running it, clear CMake cache (delete the CMakeCache.txt file in the CMake's working directory) and run CMake again.

Convert Pandas Column to DateTime

Use the to_datetime function, specifying a format to match your data.

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

How to change the button text of <input type="file" />?

Simply

<label class="btn btn-primary">
  <i class="fa fa-image"></i> Your text here<input type="file" style="display: none;"  name="image">
</label>

[Edit with snippet]

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<label class="btn btn-primary">_x000D_
<i class="fa fa-image"></i> Your text here<input type="file" style="display: none;" name="image">_x000D_
</label>
_x000D_
_x000D_
_x000D_

not None test in Python

Either of the latter two, since val could potentially be of a type that defines __eq__() to return true when passed None.

CSS / HTML Navigation and Logo on same line

The <ul> is by default a block element, make it inline-block instead:

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  display:inline-block;
  vertical-align:top;
}

CodePen Demo

Only using @JsonIgnore during serialization, but not deserialization

You can use @JsonIgnoreProperties at class level and put variables you want to igonre in json in "value" parameter.Worked for me fine.

@JsonIgnoreProperties(value = { "myVariable1","myVariable2" })
public class MyClass {
      private int myVariable1;,
      private int myVariable2;
}

How to make/get a multi size .ico file?

What i do is to prepare a 512x512 PNG, the Alpha Channel is good for rounded corners or drop shadows, then I upload it to this site http://convertico.com/, and for free then it returns me a 6 sizes .ico file with 256x256, 128x128, 64x64, 48x48, 32x32 and 16x16 sizes.

Proper use of the IDisposable interface

There are things that the Dispose() operation does in the example code that might have an effect that would not occur due to a normal GC of the MyCollection object.

If the objects referenced by _theList or _theDict are referred to by other objects, then that List<> or Dictionary<> object will not be subject to collection but will suddenly have no contents. If there were no Dispose() operation as in the example, those collections would still contain their contents.

Of course, if this were the situation I would call it a broken design - I'm just pointing out (pedantically, I suppose) that the Dispose() operation might not be completely redundant, depending on whether there are other uses of the List<> or Dictionary<> that are not shown in the fragment.

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

In my case these two issue occurs in some cases like when I am trying to display the progress dialog in an activity that is not in the foreground. So, I dismiss the progress dialog in onPause of the activity lifecycle. And the issue is resolved.

Cannot start this animator on a detached view! reveal effect BUG

ANSWER: Cannot start this animator on a detached view! reveal effect

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!

ANSWER: Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

@Override
protected void onPause() {
    super.onPause();
    dismissProgressDialog();

}

private void dismissProgressDialog() {
    if(progressDialog != null && progressDialog.isShowing())
        progressDialog.dismiss();
}

$date + 1 year?

I prefer the OO approach:

$date = new \DateTimeImmutable('today'); //'today' gives midnight, leave blank for current time.
$futureDate = $date->add(\DateInterval::createFromDateString('+1 Year'))

Use DateTimeImmutable otherwise you will modify the original date too! more on DateTimeImmutable: http://php.net/manual/en/class.datetimeimmutable.php


If you just want from todays date then you can always do:

new \DateTimeImmutable('-1 Month');

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

How to set env variable in Jupyter notebook

If you're using Python, you can define your environment variables in a .env file and load them from within a Jupyter notebook using python-dotenv.

Install python-dotenv:

pip install python-dotenv

Load the .env file in a Jupyter notebook:

%load_ext dotenv
%dotenv

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

AngularJS ng-style with a conditional expression

simple example:

<div ng-style="isTrue && {'background-color':'green'} || {'background-color': 'blue'}" style="width:200px;height:100px;border:1px solid gray;"></div>

{'background-color':'green'} RETURN true

OR the same result:

<div ng-style="isTrue && {'background-color':'green'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

other conditional possibility:

<div ng-style="count === 0 && {'background-color':'green'}  || count === 1 && {'background-color':'yellow'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

Add this in the head:

<link rel="stylesheet" type="text/css" href="/path/to/easyscrolltable.css">
<script src="/path/to/easyscrolltable.js"></script>

Javascript:

$('table.ytable').EasyScrollableTable({
    'top'  : 1,  
    'left' : 1,  
    'class': '',
    'width': '100%',
    'height': 'auto',
    'footer': false,
    'hover': true
});

How do I view cookies in Internet Explorer 11 using Developer Tools

I think I found what you are looking for since I was also looking for it.

You have to follow Pawel's steps and then go to the key that is "Cookie". This will open a submenu with all the cookies and it specifies their name, value, domain, etc...

enter image description here

Respectively the values are: Key, Value, Expiration Date, Domain, Path.

This shows all the keys for this domain.

So again to get there:

  1. Go to Network.
  2. Capture Traffic, green triangle.
  3. Go to Details.
  4. Go to the "Cookie" key that has a gibberish value. (_utmc=xxxxx;something=ajksdhfa) etc...

Is there a way to avoid null check before the for-each loop iteration starts?

It's already 2017, and you can now use Apache Commons Collections4

The usage:

for(Object obj : CollectionUtils.emptyIfNull(list1)){
    // Do your stuff
}

python plot normal distribution

import math  
import matplotlib.pyplot as plt
import numpy
import pandas as pd


def normal_pdf(x, mu=0, sigma=1):
    sqrt_two_pi = math.sqrt(math.pi * 2)
    return math.exp(-(x - mu) ** 2 / 2 / sigma ** 2) / (sqrt_two_pi * sigma)


df = pd.DataFrame({'x1': numpy.arange(-10, 10, 0.1), 'y1': map(normal_pdf, numpy.arange(-10, 10, 0.1))})

plt.plot('x1', 'y1', data=df, marker='o', markerfacecolor='blue', markersize=5, color='skyblue', linewidth=1)
plt.show()

enter image description here

How to toggle a boolean?

Let's see this in action:

_x000D_
_x000D_
var b = true;_x000D_
_x000D_
console.log(b); // true_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // false_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // true
_x000D_
_x000D_
_x000D_

Anyways, there is no shorter way than what you currently have.

How to subtract 30 days from the current datetime in mysql?

To anyone who doesn't want to use DATE_SUB, use CURRENT_DATE:

SELECT CURRENT_DATE - INTERVAL 30 DAY

How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify.

Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.

/* Mockito */  verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));

Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T where Hamcrest matcher methods return Matcher objects (of type Matcher<T>).

Mockito matchers are invoked through static methods such as eq, any, gt, and startsWith on org.mockito.Matchers and org.mockito.AdditionalMatchers. There are also adapters, which have changed across Mockito versions:

  • For Mockito 1.x, Matchers featured some calls (such as intThat or argThat) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T> extended org.hamcrest.Matcher<T>, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.
  • For Mockito 2.0+, Mockito no longer has a direct dependency on Hamcrest. Matchers calls phrased as intThat or argThat wrap ArgumentMatcher<T> objects that no longer implement org.hamcrest.Matcher<T> but are used in similar ways. Hamcrest adapters such as argThat and intThat are still available, but have moved to MockitoHamcrest instead.

Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:

/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));

In the above statement: foo.setPowerLevel is a method that accepts an int. is(greaterThan(9000)) returns a Matcher<Integer>, which wouldn't work as a setPowerLevel argument. The Mockito matcher intThat wraps that Hamcrest-style Matcher and returns an int so it can appear as an argument; Mockito matchers like gt(9000) would wrap that entire expression into a single call, as in the first line of example code.

What matchers do/return

when(foo.quux(3, 5)).thenReturn(true);

When not using argument matchers, Mockito records your argument values and compares them with their equals methods.

when(foo.quux(eq(3), eq(5))).thenReturn(true);    // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different

When you call a matcher like any or gt (greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture() it stores a matcher that saves its argument instead for later inspection.

Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List<String> for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any() or argThat(...), which can cause a NullPointerException if trying to "auto-unbox" a null primitive value.

Matchers like eq and gt take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

Implementation details

Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.

Most matcher calls only add to this stack, with an exception for matchers like and, or, and not. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:

when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6]      [5]  [1]       [4] [2]     [3]

This will:

  1. Add anyInt() to the stack.
  2. Add gt(10) to the stack.
  3. Add lt(20) to the stack.
  4. Remove gt(10) and lt(20) and add and(gt(10), lt(20)).
  5. Call foo.quux(0, 0), which (unless otherwise stubbed) returns the default value false. Internally Mockito marks quux(int, int) as the most recent call.
  6. Call when(false), which discards its argument and prepares to stub method quux(int, int) identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any() matcher for its first argument and and(gt(10), lt(20)) for its second argument and clears the stack.

This demonstrates a few rules:

  • Mockito can't tell the difference between quux(anyInt(), 0) and quux(0, anyInt()). They both look like a call to quux(0, 0) with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.

  • Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.

    int between10And20 = and(gt(10), lt(20));
    /* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
    // Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
    
    public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
    /* OK */  when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
    // The helper method calls the matcher methods in the right order.
    
  • The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when or verify, but Mockito can't check that automatically. You can check manually with Mockito.validateMockitoUsage().

  • In a call to when, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values). doReturn and doAnswer (etc) do not invoke the actual method and are often a useful alternative.

  • If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq matcher), Mockito would check the stack length against that call instead, and likely fail.

  • If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.

Common problems

  • InvalidUseOfMatchersException:

    • Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when or verify call. Matchers should never be used as stubbed return values or fields/variables.

    • Check that you're not calling a mock as a part of providing a matcher argument.

    • Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.

  • NullPointerException with primitive arguments: (Integer) any() returns null while any(Integer.class) returns 0; this can cause a NullPointerException if you're expecting an int instead of an Integer. In any case, prefer anyInt(), which will return zero and also skip the auto-boxing step.

  • NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null), which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

General troubleshooting

  • Use MockitoJUnitRunner, or explicitly call validateMockitoUsage in your tearDown or @After method (which the runner would do for you automatically). This will help determine whether you've misused matchers.

  • For debugging purposes, add calls to validateMockitoUsage in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.

How can I make Bootstrap columns all the same height?

cheeky jquery solution if anyone's interested. Just make sure all your cols (el) have a common classname...works responsively too if you bind it to $(window).resize

function equal_cols(el)
{
    var h = 0;
    $(el).each(function(){
        $(this).css({'height':'auto'});
        if($(this).outerHeight() > h)
        {
            h = $(this).outerHeight();
        }
    });
    $(el).each(function(){
        $(this).css({'height':h});
    });
}

Usage

$(document).ready(function(){
   equal_cols('.selector');
});

Note: This post has been edited as per @Chris' comment out that the code was only set the last highest height in the $.each() function

Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

Update your gradle version.

Go to your project level build.gradle file and make sure you are using the latest version of gradle.

remove first element from array and return the array minus the first element

This can be done in one line with lodash _.tail:

_x000D_
_x000D_
var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
console.log(_.tail(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Android and Facebook share intent

Here is something I did which open Facebook App with Link

shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setComponent(new ComponentName("com.facebook.katana",
                    "com.facebook.katana.activity.composer.ImplicitShareIntentHandler"));

shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,  videoUrl);

comparing 2 strings alphabetically for sorting purposes

Lets look at some test cases - try running the following expressions in your JS console:

"a" < "b"

"aa" < "ab"

"aaa" < "aab"

All return true.

JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.

In your case it works like so -

1 . "a?aaa" < "?a?b"

compares the first two "a" characters - all equal, lets move to the next character.

2 . "a?a??aa" < "a?b??"

compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.

Clear the value of bootstrap-datepicker

I found the best anwser, it work for me. Clear the value of bootstrap-datepicker:

$('#datepicker').datepicker('setDate', null);

Add value for boostrap-datepicker:

$('#datepicker').datepicker('setDate', datePicker);

Importing variables from another file?

Import file1 inside file2:

To import all variables from file1 without flooding file2's namespace, use:

import file1

#now use file1.x1, file2.x2, ... to access those variables

To import all variables from file1 to file2's namespace( not recommended):

from file1 import *
#now use x1, x2..

From the docs:

While it is valid to use from module import * at module level it is usually a bad idea. For one, this loses an important property Python otherwise has — you can know where each toplevel name is defined by a simple “search” function in your favourite editor. You also open yourself to trouble in the future, if some module grows additional functions or classes.

How can I plot separate Pandas DataFrames as subplots?

Building on @joris response above, if you have already established a reference to the subplot, you can use the reference as well. For example,

ax1 = plt.subplot2grid((50,100), (0, 0), colspan=20, rowspan=10)
...

df.plot.barh(ax=ax1, stacked=True)

How to use filesaver.js

wll it looks like I found the answer, although I havent tested it yet

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

from this page https://github.com/eligrey/FileSaver.js

How to round an image with Glide library?

With glide library you can use this code:

Glide.with(context)
    .load(imageUrl)
    .asBitmap()
    .placeholder(R.drawable.user_pic)
    .centerCrop()
    .into(new BitmapImageViewTarget(img_profPic) {
        @Override
        protected void setResource(Bitmap resource) {
            RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource);

            circularBitmapDrawable.setCircular(true);
            img_profPic.setImageDrawable(circularBitmapDrawable);
        }
    });

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

Most likely, the problem is that you're using a relative file path to open the file, but the current working directory isn't set to what you think it is.

It's a common misconception that relative paths are relative to the location of the python script, but this is untrue. Relative file paths are always relative to the current working directory, and the current working directory doesn't have to be the location of your python script.

You have three options:

  • Use an absolute path to open the file:

    file = open(r'C:\path\to\your\file.yaml')
    
  • Generate the path to the file relative to your python script:

    from pathlib import Path
    
    script_location = Path(__file__).absolute().parent
    file_location = script_location / 'file.yaml'
    file = file_location.open()
    

    (See also: How do I get the path and name of the file that is currently executing?)

  • Change the current working directory before opening the file:

    import os
    
    os.chdir(r'C:\path\to\your\file')
    file = open('file.yaml')
    

Other common mistakes that could cause a "file not found" error include:

  • Accidentally using escape sequences in a file path:

    path = 'C:\Users\newton\file.yaml'
    # Incorrect! The '\n' in 'Users\newton' is a line break character!
    

    To avoid making this mistake, remember to use raw string literals for file paths:

    path = r'C:\Users\newton\file.yaml'
    # Correct!
    

    (See also: Windows path in Python)

  • Forgetting that Windows doesn't display file extensions:

    Since Windows doesn't display known file extensions, sometimes when you think your file is named file.yaml, it's actually named file.yaml.yaml. Double-check your file's extension.

Python update a key in dict if it doesn't exist

You do not need to call d.keys(), so

if key not in d:
    d[key] = value

is enough. There is no clearer, more readable method.

You could update again with dict.get(), which would return an existing value if the key is already present:

d[key] = d.get(key, value)

but I strongly recommend against this; this is code golfing, hindering maintenance and readability.

Stopping Docker containers by image name - Ubuntu

In my case --filter ancestor=<image-name> was not working, so the following command cleaned up the Docker container for me:

docker rm $(docker stop $(docker ps -a -q --filter "name=container_name_here" --format="{{.ID}}"))

How to compare timestamp dates with date-only parameter in MySQL?

SELECT * FROM table WHERE timestamp >= '2012-05-05 00:00:00' 
    AND timestamp <= '2012-05-05 23:59:59'

Python Dictionary Comprehension

you can't hash a list like that. try this instead, it uses tuples

d[tuple([i for i in range(1,11)])] = True

jQuery DIV click, with anchors

<div class="info">
   <h2>Takvim</h2>
   <a href="item-list.php"> Click Me !</a>
</div>


$(document).delegate("div.info", "click", function() {
   window.location = $(this).find("a").attr("href");
});

Checking if float is an integer

if (fmod(f, 1) == 0.0) {
  ...
}

Don't forget math.h and libm.

Check whether an input string contains a number in javascript

This code also helps in, "To Detect Numbers in Given String" when numbers found it stops its execution.

function hasDigitFind(_str_) {
  this._code_ = 10;  /*When empty string found*/
  var _strArray = [];

  if (_str_ !== '' || _str_ !== undefined || _str_ !== null) {
    _strArray = _str_.split('');
    for(var i = 0; i < _strArray.length; i++) {
      if(!isNaN(parseInt(_strArray[i]))) {
        this._code_ = -1;
        break;
      } else {
        this._code_ = 1;
      }
    }

  }
  return this._code_;
}

Missing Authentication Token while accessing API Gateway?

I just had the same issue and it seems it also shows this message if the resource cannot be found.

In my case I had updated the API, but forgotten to redeploy. The issue was resolved after deploying the updated API to my stage.

How to remove first 10 characters from a string?

There is no need to specify the length into the Substring method. Therefore:

string s = hello world;
string p = s.Substring(3);

p will be:

"lo world".

The only exception you need to cater for is ArgumentOutOfRangeException if startIndex is less than zero or greater than the length of this instance.

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

Seems like answered here: https://public-inbox.org/git/[email protected]/

So in a similar way, running

$ git diff --cc $M $M^1 $M^2 $(git merge-base $M^1 $M^2)

should show a combined patch that explains the state at $M relative to the states recorded in its parents and the merge base.

How to keep indent for second line in ordered lists via CSS?

CSS provides only two values for its "list-style-position" - inside and outside. With "inside" second lines are flush with the list points not with the superior line:

In ordered lists, without intervention, if you give "list-style-position" the value "inside", the second line of a long list item will have no indent, but will go back to the left edge of the list (i.e. it will left-align with the number of the item). This is peculiar to ordered lists and doesn't happen in unordered lists.

If you instead give "list-style-position" the value "outside", the second line will have the same indent as the first line.

I had a list with a border and had this problem. With "list-style-position" set to "inside", my list didn't look like I wanted it to. But with "list-style-position" set to "outside", the numbers of the list items fell outside the box.

I solved this by simply setting a wider left margin for the whole list, which pushed the whole list toward the right, back into the position it was in before.

CSS:

ol.classname {margin:0;padding:0;}

ol.classname li {margin:0.5em 0 0 0;padding-left:0;list-style-position:outside;}

HTML:

<ol class="classname" style="margin:0 0 0 1.5em;">

JUNIT testing void methods

If your method has no side effects, and doesn't return anything, then it's not doing anything.

If your method does some computation and returns the result of that computation, you can obviously enough assert that the result returned is correct.

If your code doesn't return anything but does have side effects, you can call the code and then assert that the correct side effects have happened. What the side effects are will determine how you do the checks.

In your example, you are calling static methods from your non-returning functions, which makes it tricky unless you can inspect that the result of all those static methods are correct. A better way - from a testing point of view - is to inject actual objects in that you call methods on. You can then use something like EasyMock or Mockito to create a Mock Object in your unit test, and inject the mock object into the class. The Mock Object then lets you assert that the correct functions were called, with the correct values and in the correct order.

For example:

private ErrorFile errorFile;

public void setErrorFile(ErrorFile errorFile) {
    this.errorFile = errorFile;
}

private void method1(arg1) {
    if (arg1.indexOf("$") == -1) {

        //Add an error message 
        errorFile.addErrorMessage("There is a dollar sign in the specified parameter");
    }
}

Then in your test you can write:

public void testMethod1() {
    ErrorFile errorFile = EasyMock.createMock(ErrorFile.class);
    errorFile.addErrorMessage("There is a dollar sign in the specified parameter");
    EasyMock.expectLastCall(errorFile);
    EasyMock.replay(errorFile);

    ClassToTest classToTest = new ClassToTest();
    classToTest.setErrorFile(errorFile);
    classToTest.method1("a$b");

    EasyMock.verify(errorFile); // This will fail the test if the required addErrorMessage call didn't happen
}

How to get last 7 days data from current datetime to last 7 days in sql server

DATEADD and GETDATE functions might not work in MySQL database. so if you are working with MySQL database, then the following command may help you.

select id, NewsHeadline as news_headline,    
NewsText as news_text,    
state, CreatedDate as created_on    
from News    
WHERE CreatedDate>= DATE_ADD(CURDATE(), INTERVAL -3 DAY);

I hope it will help you

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

As Umesh Patil answer have comment say that there is problem. I try to edit answer and get reject. And get suggest to post new answer. This code should solve problem they have (Shashi Roy, Gaven, John Higgins).

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

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

How can I convert ArrayList<Object> to ArrayList<String>?

A simple solution:

List<Object> lst  =listOfTypeObject;   
ArrayList<String> aryLst = new ArrayList<String>();
    for (int i = 0; i < lst.size(); i++) {
        aryLst.add(lst.get(i).toString());
    }

Note: this works when the list contains all the elements of datatype String.

matplotlib colorbar in each subplot

In plt.colorbar(z1_plot,cax=ax1), use ax= instead of cax=, i.e. plt.colorbar(z1_plot,ax=ax1)

How to fix error Base table or view not found: 1146 Table laravel relationship table?

try checking in the app if you are using the tables before it's created such as appServiceProvider.php

you might be calling the table without being created it, if you are, comment it then run php artisan migrate.

Getting time difference between two times in PHP

<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>

Moving Panel in Visual Studio Code to right side

I'm using Visual Studio Code v1.24.0 on a Mac.

By default, the Panel will appear on the bottom (You can change the default as well. Please refer to @Forres' answer: Moving Panel in Visual Studio Code to right side)

Here's the bottom/right toggle button for VS Code Panel:

enter image description here

Once I click on this button, the Panel moves to the right.

enter image description here

Moving it back is a little tricky though. As you can see, some of the buttons are hidden. This is because the width of the panel when it's aligned right is too small. We need to expand the column to see all the buttons.

This is how it'll look upon expansion:

enter image description here

Now, if you want to move the Panel back to the bottom, click on the toggle bottom/top button again.

What is the reason behind "non-static method cannot be referenced from a static context"?

The essence of object oriented programming is encapsulating logic together with the data it operates on.

Instance methods are the logic, instance fields are the data. Together, they form an object.

public class Foo
{
    private String foo;
    public Foo(String foo){ this.foo = foo; }
    public getFoo(){ return this.foo; }

    public static void main(String[] args){
        System.out.println( getFoo() );
    }
}

What could possibly be the result of running the above program?

Without an object, there is no instance data, and while the instance methods exist as part of the class definition, they need an object instance to provide data for them.

In theory, an instance method that does not access any instance data could work in a static context, but then there isn't really any reason for it to be an instance method. It's a language design decision to allow it anyway rather than making up an extra rule to forbid it.

How to get current language code with Swift?

Swift 3 & 4 & 4.2 & 5

Locale.current.languageCode does not compile regularly. Because you did not implemented localization for your project.

You have two possible solutions

1) String(Locale.preferredLanguages[0].prefix(2)) It returns phone lang properly.

If you want to get the type en-En, you can use Locale.preferredLanguages[0]

2) Select Project(MyApp)->Project (not Target)-> press + button into Localizations, then add language which you want.

Android - Share on Facebook, Twitter, Mail, ecc

Use this

Facebook - "com.facebook.katana"
Twitter - "com.twitter.android"
Instagram - "com.instagram.android"
Pinterest - "com.pinterest"



SharingToSocialMedia("com.facebook.katana")


public void SharingToSocialMedia(String application) {

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM, bmpUri);

    boolean installed = checkAppInstall(application);
    if (installed) {
        intent.setPackage(application);
        startActivity(intent);
    } else {
        Toast.makeText(getApplicationContext(),
                "Installed application first", Toast.LENGTH_LONG).show();
    }

}


 private boolean checkAppInstall(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}

How to modify existing, unpushed commit messages?

On this question there are a lot of answers, but none of them explains in super detail how to change older commit messages using Vim. I was stuck trying to do this myself, so here I'll write down in detail how I did this especially for people who have no experience in Vim!

I wanted to change my five latest commits that I already pushed to the server. This is quite 'dangerous' because if someone else already pulled from this, you can mess things up by changing the commit messages. However, when you’re working on your own little branch and are sure no one pulled it you can change it like this:

Let's say you want to change your five latest commits, and then you type this in the terminal:

git rebase -i HEAD~5

*Where 5 is the number of commit messages you want to change (so if you want to change the 10th to last commit, you type in 10).

This command will get you into Vim there you can ‘edit’ your commit history. You’ll see your last five commits at the top like this:

pick <commit hash> commit message

Instead of pick you need to write reword. You can do this in Vim by typing in i. That makes you go in to insert mode. (You see that you’re in insert mode by the word INSERT at the bottom.) For the commits you want to change, type in reword instead of pick.

Then you need to save and quit this screen. You do that by first going in to ‘command-mode’ by pressing the Escbutton (you can check that you’re in command-mode if the word INSERT at the bottom has disappeared). Then you can type in a command by typing :. The command to save and quit is wq. So if you type in :wq you’re on the right track.

Then Vim will go over every commit message you want to reword, and here you can actually change the commit messages. You’ll do this by going into insert mode, changing the commit message, going into the command-mode, and save and quit. Do this five times and you’re out of Vim!

Then, if you already pushed your wrong commits, you need to git push --force to overwrite them. Remember that git push --force is quite a dangerous thing to do, so make sure that no one pulled from the server since you pushed your wrong commits!

Now you have changed your commit messages!

(As you see, I'm not that experienced in Vim, so if I used the wrong 'lingo' to explain what's happening, feel free to correct me!)

Authentication issue when debugging in VS2013 - iis express

As I was researching this I found my answer, but can't find the answer on the internet, so I thought I'd share this:

I fixed my issue by modifying my applicationhost.config file. My file was saved in the "\My Documents\IISExpress\config" folder.

It seems that VS2013 was ignoring my web.config file and applying different authentication methods.

I had to modify this portion of the file to look like the below. In truth, I only modified the anonymousAuthentication to be false and the windowsAuthentication mode to true.

<authentication>

  <anonymousAuthentication enabled="false" userName="" />

  <basicAuthentication enabled="false" />

  <clientCertificateMappingAuthentication enabled="false" />

  <digestAuthentication enabled="false" />

  <iisClientCertificateMappingAuthentication enabled="false">
  </iisClientCertificateMappingAuthentication>

  <windowsAuthentication enabled="true">
    <providers>
      <add value="Negotiate" />
      <add value="NTLM" />
    </providers>
  </windowsAuthentication>

</authentication>

How to use sys.exit() in Python

you didn't import sys in your code, nor did you close the () when calling the function... try:

import sys
sys.exit()

jQuery hover and class selector

This can be achieved in CSS using the :hover pseudo-class. (:hover doesn't work on <div>s in IE6)

HTML:

<div id="menu">
   <a class="menuItem" href=#>Bla</a>
   <a class="menuItem" href=#>Bla</a>
   <a class="menuItem" href=#>Bla</a>
</div>

CSS:

.menuItem{
  height:30px;
  width:100px;
  background-color:#000;
}
.menuItem:hover {
  background-color:#F00;
}

How to correct TypeError: Unicode-objects must be encoded before hashing?

import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())

Grid of responsive squares

You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :

Responsive 3x3 square grid Responsive square images in a 3x3 grid

Now let's see how to make these fancy responsive squares!



1. Making the responsive squares :

The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.

As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :

HTML :

 <div></div>

CSS

div {
    width: 30%;
    padding-bottom: 30%; /* = width for a square aspect ratio */
}

Here is a simple layout example of 3*3 squares grid using the code above.

With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.

 Aspect ratio  |  padding-bottom  |  for 30% width
------------------------------------------------
    1:1        |  = width         |    30%
    1:2        |  width x 2       |    60%
    2:1        |  width x 0.5     |    15%
    4:3        |  width x 0.75    |    22.5%
    16:9       |  width x 0.5625  |    16.875%




2. Adding content inside the squares

As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute; and put the content inside them. This will take the content out of the flow and keep the size of the square.

Don't forget to add position:relative; on the parent divs so the absolute children are positioned/sized relatively to their parent.

Let's add some content to our 3x3 grid of squares :

HTML :

<div class="square">
    <div class="content">
        .. CONTENT HERE ..
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}

RESULT <-- with some formatting to make it pretty!



3.Centering the content

Horizontally :

This is pretty easy, you just need to add text-align:center to .content.
RESULT

Vertical alignment

This becomes serious! The trick is to use

display:table;
/* and */
display:table-cell;
vertical-align:middle;

but we can't use display:table; on .square or .content divs because it conflicts with position:absolute; so we need to create two children inside .content divs. Our code will be updated as follow :

HTML :

<div class="square">
    <div class="content">
        <div class="table">
            <div class="table-cell">
                ... CONTENT HERE ...
            </div>
        </div>
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}
.table{
    display:table;
    height:100%;
    width:100%;
}
.table-cell{
    display:table-cell;
    vertical-align:middle;
    height:100%;
    width:100%;
}




We have now finished and we can take a look at the result here :

LIVE FULLSCREEN RESULT

editable fiddle here


(HTML) Download a PDF file instead of opening them in browser when clicked

You can use

Response.AddHeader("Content-disposition", "attachment; filename=" + Name);

Check out this example:

http://www.codeproject.com/KB/aspnet/textfile.aspx

This goes for ASP.NET. I am sure you can find similar solutions in all other server side languages. However there's no javascript solution to the best of my knowledge.

Command to list all files in a folder as well as sub-folders in windows

An addition to the answer: when you do not want to list the folders, only the files in the subfolders, use /A-D switch like this:

dir ..\myfolder /b /s /A-D /o:gn>list.txt

Bootstrap 3 - jumbotron background image effect

I think what you are looking for is to keep the background image fixed and just move the content on scroll. For that you have to simply use the following css property :

background-attachment: fixed;

How to append in a json file in Python?

You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.

Can I set the cookies to be used by a WKWebView?

After looking through various answers here and not having any success, I combed through the WebKit documentation and stumbled upon the requestHeaderFields static method on HTTPCookie, which converts an array of cookies into a format suitable for a header field. Combining this with mattr's insight of updating the URLRequest before loading it with the cookie headers got me through the finish line.

Swift 4.1, 4.2, 5.0:

var request = URLRequest(url: URL(string: "https://example.com/")!)
let headers = HTTPCookie.requestHeaderFields(with: cookies)
for (name, value) in headers {
    request.addValue(value, forHTTPHeaderField: name)
}

let webView = WKWebView(frame: self.view.frame)
webView.load(request)

To make this even simpler, use an extension:

extension WKWebView {
    func load(_ request: URLRequest, with cookies: [HTTPCookie]) {
        var request = request
        let headers = HTTPCookie.requestHeaderFields(with: cookies)
        for (name, value) in headers {
            request.addValue(value, forHTTPHeaderField: name)
        }

        load(request)
    }
}

Now it just becomes:

let request = URLRequest(url: URL(string: "https://example.com/")!)
let webView = WKWebView(frame: self.view.frame)
webView.load(request, with: cookies)

This extension is also available in LionheartExtensions if you just want a drop-in solution. Cheers!

update columns values with column of another table based on condition

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE table2.id=table1.id AND table2.item=table1.item);

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1
print(len(num))

Instead of use ths,

data = [1,2,3,4]
print(len(data))

dplyr change many data types

A more general way of achieving column type transformation is as follows:

If you want to transform all your factor columns to character columns, e.g., this can be done using one pipe:

df %>%  mutate_each_( funs(as.character(.)), names( .[,sapply(., is.factor)] ))

Deep-Learning Nan loss reasons

There are lots of things I have seen make a model diverge.

  1. Too high of a learning rate. You can often tell if this is the case if the loss begins to increase and then diverges to infinity.

  2. I am not to familiar with the DNNClassifier but I am guessing it uses the categorical cross entropy cost function. This involves taking the log of the prediction which diverges as the prediction approaches zero. That is why people usually add a small epsilon value to the prediction to prevent this divergence. I am guessing the DNNClassifier probably does this or uses the tensorflow opp for it. Probably not the issue.

  3. Other numerical stability issues can exist such as division by zero where adding the epsilon can help. Another less obvious one if the square root who's derivative can diverge if not properly simplified when dealing with finite precision numbers. Yet again I doubt this is the issue in the case of the DNNClassifier.

  4. You may have an issue with the input data. Try calling assert not np.any(np.isnan(x)) on the input data to make sure you are not introducing the nan. Also make sure all of the target values are valid. Finally, make sure the data is properly normalized. You probably want to have the pixels in the range [-1, 1] and not [0, 255].

  5. The labels must be in the domain of the loss function, so if using a logarithmic-based loss function all labels must be non-negative (as noted by evan pu and the comments below).

Float right and position absolute doesn't work together

Generally speaking, float is a relative positioning statement, since it specifies the position of the element relative to its parent container (floating to the right or left). This means it's incompatible with the position:absolute property, because position:absolute is an absolute positioning statement. You can either float an element and allow the browser to position it relative to its parent container, or you can specify an absolute position and force the element to appear in a certain position regardless of its parent. If you want an absolutely-positioned element to appear on the right side of the screen, you can use position: absolute; right: 0;, but this will cause the element to always appear on the right edge of the screen regardless of how wide its parent div is (so it won't be "at the right of its parent div").

What is a regular expression which will match a valid domain name without a subdomain?

^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,7}$

[domain - lower case letters and 0-9 only] [can have a hyphen] + [TLD - lower case only, must be beween 2 and 7 letters long]
http://rubular.com/ is brilliant for testing regular expressions!
Edit: Updated TLD maximum to 7 characters for '.rentals' as Dan Caddigan pointed out.

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

This problem happens when a process tries to manipulate an Activity whose onStop() has been called. It's not necessarily tied to fragment transaction but also other methods like onBackPressed().

In addition to AsyncTask, another source of such problem is the misplacement of bus pattern's subscription. Usually Event Bus or RxBus's subscription is registered during Activity's onCreate and de-registered in onDestroy. If a new Activity starts and publishes an event intercepted by subscribers from the previous Activity then it may produce this error. If this happens then one solution is to move subscription registration and de-registration to onStart() and onStop().

$(document).ready(function() is not working

Did you load jQuery in head section? Did you load it correctly?

<head>
   <script src="scripts/jquery.js"></script>
   ...
</head>

This code assumes jquery.js is in scripts directory. (You can change file name if you like)

You can also use jQuery as hosted by Google:

<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
   ...
</head>

As per your comment:

Apparently, your web server is not configured to return jQuery-1.6.1.js on requesting /webProject/jquery-1.6.1.js. There may be numerous reasons for this, such as wrong file name, folder name, routing settings, etc. You need to create another question and describe your 404 in greater details (such as local file name, operation system, webserver name and settings).

Again, you can use jQuery as provided by Google (see above), however you still might want to find out why some local files don't get served on request.

ORA-06508: PL/SQL: could not find program unit being called

I suspect you're only reporting the last error in a stack like this:

ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"

If so, that's because your package is stateful:

The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.

When you recompile the state is lost:

If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.

After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...

You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.

But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).

MySQL: ALTER TABLE if column not exists

Sometimes it may happen that there are multiple schema created in a database.

So to be specific schema we need to target, so this will help to do it.

SELECT count(*) into @colCnt FROM information_schema.columns WHERE table_name = 'mytable' AND column_name = 'mycolumn' and table_schema = DATABASE();
IF @colCnt = 0 THEN
    ALTER TABLE `mytable` ADD COLUMN `mycolumn` VARCHAR(20) DEFAULT NULL;
END IF;

Java error: Implicit super constructor is undefined for default constructor

Eclipse will give this error if you don't have call to super class constructor as a first statement in subclass constructor.

Change Bootstrap tooltip color

This is already been answered right but i think i should give my opinion too. Like cozen says this is a border, and for it to work you must specify the classes to format this in the same way that bootstrap specifies it. So, you can do this

.tooltip .tooltip-inner {background-color: #00a8c4; color: black;} 
.tooltip.top .tooltip-arrow {border-top-color: #00a8c4;}

or you can do the next one, just for the tooltip-arrow but you must add the !important, so that it overwrites the bootstrap css

.tooltip-arrow {border-top-color: #00a8c4!important;}

Converting between java.time.LocalDateTime and java.util.Date

Here is what I came up with ( and like all Date Time conundrums it is probably going to be disproved based on some weird timezone-leapyear-daylight adjustment :D )

Round-tripping: Date <<->> LocalDateTime

Given: Date date = [some date]

(1) LocalDateTime << Instant<< Date

    Instant instant = Instant.ofEpochMilli(date.getTime());
    LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

(2) Date << Instant << LocalDateTime

    Instant instant = ldt.toInstant(ZoneOffset.UTC);
    Date date = Date.from(instant);

Example:

Given:

Date date = new Date();
System.out.println(date + " long: " + date.getTime());

(1) LocalDateTime << Instant<< Date:

Create Instant from Date:

Instant instant = Instant.ofEpochMilli(date.getTime());
System.out.println("Instant from Date:\n" + instant);

Create Date from Instant (not necessary,but for illustration):

date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());

Create LocalDateTime from Instant

LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
System.out.println("LocalDateTime from Instant:\n" + ldt);

(2) Date << Instant << LocalDateTime

Create Instant from LocalDateTime:

instant = ldt.toInstant(ZoneOffset.UTC);
System.out.println("Instant from LocalDateTime:\n" + instant);

Create Date from Instant:

date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());

The output is:

Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574

Instant from Date:
2013-11-01T14:13:04.574Z

Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574

LocalDateTime from Instant:
2013-11-01T14:13:04.574

Instant from LocalDateTime:
2013-11-01T14:13:04.574Z

Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574

"date(): It is not safe to rely on the system's timezone settings..."

A quick solution whilst your rectify the incompatibilities, is to disable error reporting in your index.php file:

Insert the line below into your index.php below define( ‘_JEXEC’, 1 );

error_reporting( E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR |
E_COMPILE_WARNING );

Guid.NewGuid() vs. new Guid()

new Guid() makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).

Guid.NewGuid() makes an actual guid with a unique value, what you probably want.

Set object property using reflection

Yes, using System.Reflection:

using System.Reflection;

...

    string prop = "name";
    PropertyInfo pi = myObject.GetType().GetProperty(prop);
    pi.SetValue(myObject, "Bob", null);

How to split a string into a list?

str.split()

Return a list of the words in the string, using sep as the delimiter ... If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

>>> line="a sentence with a few words"
>>> line.split()
['a', 'sentence', 'with', 'a', 'few', 'words']
>>> 

How to reset or change the passphrase for a GitHub SSH key?

  1. Log in to your github account.
  2. Go to the "Settings" page (the "wrench and screwdriver" icon in the top right corner of the page).
  3. Go to "SSH keys" page.
  4. Generate a new SSH key (probably studying the links provided by github on that page).
  5. Add your new key using the "Add SSH key" link.
  6. Verify your new key works.
  7. Make gitub forget your old key by using the "Delete" link next to it in the list of known keys.

Oracle: how to set user password unexpire?

If you create a user using a profile like this:

CREATE PROFILE my_profile LIMIT
       PASSWORD_LIFE_TIME 30;
ALTER USER scott PROFILE my_profile;

then you can change the password lifetime like this:

ALTER PROFILE my_profile LIMIT
  PASSWORD_LIFE_TIME UNLIMITED;

I hope that helps.

How to delete stuff printed to console by System.out.println()?

Just to add to BalusC's anwswer...

Invoking System.out.print("\b \b") repeatedly with a delay gives an exact same behavior as when we hit backspaces in {Windows 7 command console / Java 1.6}

Can I set variables to undefined or pass undefined as an argument?

The best way to check for a null values is

if ( testVar !== null )
{
    // do action here
}

and for undefined

if ( testVar !== undefined )
{
    // do action here
}

You can assign a avariable with undefined.

testVar = undefined;
//typeof(testVar) will be equal to undefined.

How to remove close button on the jQuery UI dialog?

Robert MacLean's answer did not work for me.

This however does work for me:

$("#div").dialog({
   open: function() { $(".ui-dialog-titlebar-close").hide(); }
});

Location of the mongodb database on mac

I have just installed mongodb 3.4 with homebrew.(brew install mongodb) It looks for /data/db by default.

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

Here is the output of mongod execution.

get all characters to right of last dash

string tail = test.Substring(test.LastIndexOf('-') + 1);

Spring boot Security Disable security

As previously multiple solutions mentioned to disable security through commenting of

@EnableWebSecurity

annotation and other is through properties in application.properties or yml. But those properties are showing as deprecated in latest spring boot version.

So, I would like to share another approach to configure default username and password in your application-dev.properties or application-dev.yml and use them to login into swagger and etc in development environment.

spring.security.user.name=admin
spring.security.user.password=admin

So, this approach will also provides you some kind of security as well and you can share this information with your development team. You can also configure user roles as well, but its not required in development level.

How to convert String to Date value in SAS?

input(char_val, date9.);

You can consider to convert it to word format using input(char_val, worddate.)

You can get a lot in this page http://v8doc.sas.com/sashtml/lrcon/zenid-63.htm

Is there an equivalent of 'which' on the Windows command line?

I am using GOW (GNU on Windows) which is a light version of Cygwin. You can grab it from GitHub here.

GOW (GNU on Windows) is the lightweight alternative to Cygwin. It uses a convenient Windows installer that installs about 130 extremely useful open source UNIX applications compiled as native win32 binaries. It is designed to be as small as possible, about 10 MB, as opposed to Cygwin which can run well over 100 MB depending upon options. - About Description(Brent R. Matzelle)

A screenshot of a list of commands included in GOW:

Enter image description here

How to subscribe to an event on a service in Angular2?

Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945

Also, the Angular docs now have a cookbook example that uses a Subject.


Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.

nav.service.ts

import {EventEmitter} from 'angular2/core';
export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emitNavChangeEvent(number) {
    this.navchange.emit(number);
  }
  getNavChangeEmitter() {
    return this.navchange;
  }
}

components.ts

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number = 0;
  subscription: any;
  constructor(private navService:NavService) {}
  ngOnInit() {
    this.subscription = this.navService.getNavChangeEmitter()
      .subscribe(item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item = 1;
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emitNavChangeEvent(item);
  }
}

Plunker

How to style SVG with external CSS?

@leo here is the angularJS version, thanks again

G.directive ( 'imgInlineSvg', function () {

return {
    restrict : 'C',
    scope : true,
    link : function ( scope, elem, attrs ) {

        if ( attrs.src ) {

            $ ( attrs ).each ( function () {
                var imgID    = attrs.class;
                var imgClass = attrs.class;
                var imgURL   = attrs.src;

                $.get ( imgURL, function ( data ) {

                    var $svg = $ ( data ).find ( 'svg' );
                    if ( typeof imgID !== 'undefined' ) {
                        $svg = $svg.attr ( 'id', imgID );
                    }

                    if ( typeof imgClass !== 'undefined' ) {
                        $svg = $svg.attr ( 'class', imgClass + ' replaced-svg' );
                    }

                    $svg = $svg.removeAttr ( 'xmlns:a' );

                    elem.replaceWith ( $svg );

                } );

            } );
        }

    }

}

} );

How to print from Flask @app.route to python console

I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True). You can also disable buffering by setting the PYTHONUNBUFFERED environment variable (to any non-empty string).

Pass Parameter to Gulp Task

There's an official gulp recipe for this using minimist.

https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md

The basics are using minimist to separate the cli arguments and combine them with known options:

var options = minimist(process.argv.slice(2), knownOptions);

Which would parse something like

$ gulp scripts --env development

More complete info in the recipe.

Java - creating a new thread

The goal was to write code to call start() and join() in one place. Parameter anonymous class is an anonymous function. new Thread(() ->{})

new Thread(() ->{
        System.out.println("Does it work?");
        Thread.sleep(1000);
        System.out.println("Nope, it doesnt...again.");       
}){{start();}}.join();

In the body of an anonymous class has instance-block that calls start(). The result is a new instance of class Thread, which is called join().

how to convert date to a format `mm/dd/yyyy`

As your data already in varchar, you have to convert it into date first:

select convert(varchar(10), cast(ts as date), 101) from <your table>

Could someone explain this for me - for (int i = 0; i < 8; i++)

for(<first part>; <second part>; <third part>)
{
    DoStuff();
}

This code is evaluated like this:

  1. Run <first part>
  2. If <second part> is false, skip to the end
  3. DoStuff();
  4. Run <third part>
  5. Goto 2

So for your example:

for (int i = 0; i < 8; i++)
{
    DoStuff();
}
  1. Set i to 0.
  2. If i is not less than 8, skip to the end.
  3. DoStuff();
  4. i++
  5. Goto 2

So the loop runs one time with i set to each value from 0 to 7. Note that i is incremented to 8, but then the loop ends immediately afterwards; it does not run with i set to 8.

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

c# open a new form then close the current form?

use this code snippet in your form1.

public static void ThreadProc()
{
Application.Run(new Form());
}

private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}

I got this from here

How to send email from SQL Server?

You can send email natively from within SQL Server using Database Mail. This is a great tool for notifying sysadmins about errors or other database events. You could also use it to send a report or an email message to an end user. The basic syntax for this is:

EXEC msdb.dbo.sp_send_dbmail  
@recipients='[email protected]',
@subject='Testing Email from SQL Server',
@body='<p>It Worked!</p><p>Email sent successfully</p>',
@body_format='HTML',
@from_address='Sender Name <[email protected]>',
@reply_to='[email protected]'

Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure. A database or Exchange admin might need to help you configure this. See http://msdn.microsoft.com/en-us/library/ms190307.aspx and http://www.codeproject.com/Articles/485124/Configuring-Database-Mail-in-SQL-Server for more information.

MySQL: Quick breakdown of the types of joins

Based on your comment, simple definitions of each is best found at W3Schools The first line of each type gives a brief explanation of the join type

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

END EDIT

In a nutshell, the comma separated example you gave of

SELECT * FROM a, b WHERE b.id = a.beeId AND ...

is selecting every record from tables a and b with the commas separating the tables, this can be used also in columns like

SELECT a.beeName,b.* FROM a, b WHERE b.id = a.beeId AND ...

It is then getting the instructed information in the row where the b.id column and a.beeId column have a match in your example. So in your example it will get all information from tables a and b where the b.id equals a.beeId. In my example it will get all of the information from the b table and only information from the a.beeName column when the b.id equals the a.beeId. Note that there is an AND clause also, this will help to refine your results.

For some simple tutorials and explanations on mySQL joins and left joins have a look at Tizag's mySQL tutorials. You can also check out Keith J. Brown's website for more information on joins that is quite good also.

I hope this helps you

How can I change the default width of a Twitter Bootstrap modal box?

Solution was taken from this page

$('#feedback-modal').modal({
    backdrop: true,
    keyboard: true
}).css({
    width: 'auto',
    'margin-left': function () {
        return -($(this).width() / 2);
    }
});

Get and set position with jQuery .offset()

var redBox = $(".post");

var greenBox = $(".post1");

var offset = redBox.offset();

$(".post1").css({'left': +offset.left});
$(".post1").html("Left :" +offset.left);

http://jsfiddle.net/va836/159/

How to validate email id in angularJs using ng-pattern

Spend some time to make it working for me.

Requirement:

single or comma separated list of e-mails with domains ending [email protected] or [email protected]

Controller:

$scope.email = {
   EMAIL_FORMAT:  /^\w+([\.-]?\w+)*@(list.)?gmail.com+((\s*)+,(\s*)+\w+([\.-]?\w+)*@(list.)?gmail.com)*$/,
   EMAIL_FORMAT_HELP: "format as '[email protected]' or comma separated '[email protected], [email protected]'"
};

HTML:

<ng-form name="emailModal">
    <div class="form-group row mb-3">
        <label for="to" class="col-sm-2 text-right col-form-label">
            <span class="form-required">*</span>
            To
        </label>
        <div class="col-sm-9">
            <input class="form-control" id="to"
                   name="To"
                   ng-required="true"
                   ng-pattern="email.EMAIL_FORMAT"
                   placeholder="{{email.EMAIL_FORMAT_HELP}}"
                   ng-model="mail.to"/>
            <small class="text-muted" ng-show="emailModal.To.$error.pattern">wrong</small>
        </div>
    </div>
</ng-form>

I found good online regex testing tool. Covered my regex with tests:

https://regex101.com/r/Dg2iAZ/6/tests

How does the "final" keyword in Java work? (I can still modify an object.)

The final keyword can be interpreted in two different ways depending on what it's used on:

Value types: For ints, doubles etc, it will ensure that the value cannot change,

Reference types: For references to objects, final ensures that the reference will never change, meaning that it will always refer to the same object. It makes no guarantees whatsoever about the values inside the object being referred to staying the same.

As such, final List<Whatever> foo; ensures that foo always refers to the same list, but the contents of said list may change over time.

How can I check whether a numpy array is empty or not?

Why would we want to check if an array is empty? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append is a frequent novice error.

Using a list in if alist: hinges on its boolean value:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

But trying to do the same with an array produces (in version 1.18):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value 
   of an empty array is ambiguous. Returning False, but in 
   future this will result in an error. Use `array.size > 0` to 
   check that an array is not empty.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

and bool(np.array([1,2]) produces the infamous ambiguity error.

edit

The accepted answer suggests size:

In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0

But I (and most others) check the shape more than the size:

In [13]: x.shape
Out[13]: (0,)

Another thing in its favor is that it 'maps' on to an empty list:

In [14]: x.tolist()
Out[14]: []

But there are other other arrays with 0 size, that aren't 'empty' in that last sense:

In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True

np.array([[],[]]) is also size 0, but shape (2,0) and len 2.

While the concept of an empty list is well defined, an empty array is not well defined. One empty list is equal to another. The same can't be said for a size 0 array.

The answer really depends on

  • what do you mean by 'empty'?
  • what are you really test for?

Using Tempdata in ASP.NET MVC - Best practice

Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek method. I would recommend reading this cool article:

MVC Tempdata , Peek and Keep confusion

How to use \n new line in VB msgbox() ...?

Module MyHelpers
    <Extension()>
    Public Function UnEscape(ByVal aString As String) As String

       Return Regex.Unescape(aString)

    End Function
End Module

Usage:

console.writeline("Ciao!\n".unEscape)

How to properly make a http web GET request

Servers sometimes compress their responses to save on bandwidth, when this happens, you need to decompress the response before attempting to read it. Fortunately, the .NET framework can do this automatically, however, we have to turn the setting on.

Here's an example of how you could achieve that.

string html = string.Empty;
string url = @"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    html = reader.ReadToEnd();
}

Console.WriteLine(html);

GET

public string Get(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

GET async

public async Task<string> GetAsync(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

POST
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public string Post(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        requestBody.Write(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

    

POST async
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

How to hide "Showing 1 of N Entries" with the dataTables.js library

It is Work for me:

language:{"infoEmpty": "No records available",}

How to read the RGB value of a given pixel in Python?

You could use the Tkinter module, which is the standard Python interface to the Tk GUI toolkit and you don't need extra download. See https://docs.python.org/2/library/tkinter.html.

(For Python 3, Tkinter is renamed to tkinter)

Here is how to set RGB values:

#from http://tkinter.unpythonic.net/wiki/PhotoImage
from Tkinter import *

root = Tk()

def pixel(image, pos, color):
    """Place pixel at pos=(x,y) on image, with color=(r,g,b)."""
    r,g,b = color
    x,y = pos
    image.put("#%02x%02x%02x" % (r,g,b), (y, x))

photo = PhotoImage(width=32, height=32)

pixel(photo, (16,16), (255,0,0))  # One lone pixel in the middle...

label = Label(root, image=photo)
label.grid()
root.mainloop()

And get RGB:

#from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py
def getRGB(image, x, y):
    value = image.get(x, y)
    return tuple(map(int, value.split(" ")))

Using Postman to access OAuth 2.0 Google APIs

The best way I found so far is to go to the Oauth playground here: https://developers.google.com/oauthplayground/

  1. Select the relevant google api category, and then select the scope inside that category in the UI.
  2. Get the authorization code by clicking "authorize API" blue button. Exchange authorization code for token by clicking the blue button.
  3. Store the OAuth2 token and use it as shown below.

In the HTTP header for the REST API request, add: "Authorization: Bearer ". Here, Authorization is the key, and "Bearer ". For example: "Authorization: Bearer za29.KluqA3vRtZChWfJDabcdefghijklmnopqrstuvwxyz6nAZ0y6ElzDT3yH3MT5"

Redirect stderr to stdout in C shell

I object the above answer and provide my own. csh DOES have this capability and here is how it's done:

xxx |& some_exec # will pipe merged output to your some_exec 

or

xxx |& cat > filename

or if you just want it to merge streams (to stdout) and not redirect to a file or some_exec:

xxx |& tee /dev/null

How can I check if a jQuery plugin is loaded?

If we're talking about a proper jQuery plugin (one that extends the fn namespace), then the proper way to detect the plugin would be:

if(typeof $.fn.pluginname !== 'undefined') { ... }

Or because every plugin is pretty much guaranteed to have some value that equates to true, you can use the shorter

if ($.fn.pluginname) { ... }

BTW, the $ and jQuery are interchangable, as the odd-looking wrapper around a plugin demonstrates:

(function($) {
    //
})(jQuery))

the closure

(function($) {
    //
})

is followed immediately by a call to that closure 'passing' jQuery as the parameter

(jQuery)

the $ in the closure is set equal to jQuery

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

Possible heap pollution via varargs parameter

Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

This can lead to "unexplainable" ClassCastExceptions.

// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0); 

@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.

However, if the method actually is not safe, users will no longer be warned.

Split array into chunks

This is the most efficient and straight-forward solution I could think of:

function chunk(array, chunkSize) {
    let chunkCount = Math.ceil(array.length / chunkSize);
    let chunks = new Array(chunkCount);
    for(let i = 0, j = 0, k = chunkSize; i < chunkCount; ++i) {
        chunks[i] = array.slice(j, k);
        j = k;
        k += chunkSize;
    }
    return chunks;
}

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

If your are working in a web service and the v2.0 assembly is a dependency that has been loaded by WcfSvcHost.exe then you must include

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" />
</startup>

in ..\Microsoft Visual Studio 10.0\Common7\IDE\ WcfSvcHost.exe.config file

This way, Visual Studio will be able to send the right information through the loader at runtime.

How to show soft-keyboard when edittext is focused

I had the same problem in various different situations, and the solutions i have found work in some but dont work in others so here is a combine solution that works in most situations i have found:

public static void showVirtualKeyboard(Context context, final View view) {
    if (context != null) {
        final InputMethodManager imm =  (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        view.clearFocus();

        if(view.isShown()) {
            imm.showSoftInput(view, 0);
            view.requestFocus();
        } else {
            view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                @Override
                public void onViewAttachedToWindow(View v) {
                    view.post(new Runnable() {
                        @Override
                        public void run() {
                            view.requestFocus();
                            imm.showSoftInput(view, 0);
                        }
                    });

                    view.removeOnAttachStateChangeListener(this);
                }

                @Override
                public void onViewDetachedFromWindow(View v) {
                    view.removeOnAttachStateChangeListener(this);
                }
            });
        }
    }
}