Programs & Examples On #Accessibility api

The classes in this package are used for development of accessibility service that provide alternative or augmented feedback to the user.They may be useful in developing applications that may help people who need alternatives to use Android phones. eg : due to physical incapabilities.

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

If you want the sum of all bars to be equal unity, weight each bin by the total number of values:

weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)

Hope that helps, although the thread is quite old...

Note for Python 2.x: add casting to float() for one of the operators of the division as otherwise you would end up with zeros due to integer division

Show DialogFragment with animation growing from a point

Have you looked at Android Developers Training on Zooming a View? Might be a good starting point.

You probably want to create a custom class extending DialogFragment to get this working.

Also, take a look at Jake Whartons NineOldAndroids for Honeycomb Animation API compatibility all the way back to API Level 1.

R - argument is of length zero in if statement

The same error message results not only for null but also for e.g. factor(0). In this case, the query must be if(length(element) > 0 & otherCondition) or better check both cases with if(!is.null(element) & length(element) > 0 & otherCondition).

How can I declare a global variable in Angular 2 / Typescript?

Here is the simplest solution w/o Service nor Observer:

Put the global variables in a file an export them.

//
// ===== File globals.ts    
//
'use strict';

export const sep='/';
export const version: string="22.2.2";    

To use globals in another file use an import statement: import * as myGlobals from 'globals';

Example:

// 
// ===== File heroes.component.ts    
//
import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {HeroService} from './hero.service';
import {HeroDetailComponent} from './hero-detail.component';
import {Hero} from './hero';
import * as myGlobals from 'globals'; //<==== this one (**Updated**)

export class HeroesComponent implements OnInit {
    public heroes: Hero[];
    public selectedHero: Hero;
    // 
    //
    // Here we access the global var reference.
    //  
    public helloString: string="hello " + myGlobals.sep + " there";

         ...

        }
    }

Thanks @eric-martinez

Equivalent of Clean & build in Android Studio?

Also you can edit your Run/Debug configuration and add clean task.

Click on the Edit configuration

Click on the Edit configuration

In the left list of available configurations choose your current configuration and then on the right side of the dialog window in the section Before launch press on plus sign and choose Run Gradle task

choose <code>Run Gradle task</code>

In the new window choose your gradle project and in the field Tasks type clean.

type <code>clean</code>

Then move your gradle clean on top of Gradle-Aware make

git: updates were rejected because the remote contains work that you do not have locally

The error possibly comes because of the different structure of the code that you are committing and that present on GitHub. You may refer to: How to deal with "refusing to merge unrelated histories" error:

$ git pull --allow-unrelated-histories
$ git push -f origin master

jquery/javascript convert date string to date

Use moment js for any date operation.

https://momentjs.com/

_x000D_
_x000D_
console.log(moment("Sunday, February 28, 2010").format('MM/DD/YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

What is the purpose of a plus symbol before a variable?

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

How can I start InternetExplorerDriver using Selenium WebDriver

I've been firefighting with this issue for the past one month. And finally I found a fruitful solution. Here are the exact steps which we followed to get it worked. I have already done Required Configuration as mentioned in this link: https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver#required-configuration

  1. Make the internet explorer protected mode settings enable/disable for all the zones. (In my case I enabled across all the zones, doesn't matter about the levels). If your organisation not allow these settings, the other solution is to create a group at active directory level and enforce our expected internet explorer settings for that group. Add your user name to that group.
  2. Install IE Webdriver tool for windows from the below link. This is from Microsoft. No need to restart your machine after installation https://www.microsoft.com/en-au/download/details.aspx?id=44069
  3. Use these Desired Capabilities for your internet explorer driver

    DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
    capabilities.setCapability("requireWindowFocus", true);  
    capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, false);
    capabilities.setCapability("ie.ensureCleanSession", true);
    

    capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true); capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, true); webDriver = new InternetExplorerDriver(capabilities);

  4. Use appropriate selenium version 2.53.1. I got it worked for the selenium version as mentioned in pom

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
    </dependency>
    
  5. Download the IEDriverServer_x64_2.53.1.zip from the below link. Make sure its 2.53.1 http://selenium-release.storage.googleapis.com/index.html?path=2.53/

  6. Now go to registry settings (regedit.exe) for the current user (Don't open regedit as an Administrator) and add TabProcGrowth for the below path in regedit

HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main

Right click on Main and add new DWORD (32 bit) and make it as 0. Remember I tried 64 bit with QWORD it didn't worked for me.

The key in this process is Step 2 which is Install IE Webdriver tool for windows

I didn't tried this method for Selenium latest version 3.0 but will give a try.

Function to get yesterday's date in Javascript in format DD/MM/YYYY

You override $today in the if statement.

if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;

It is then not a Date() object anymore - hence the error.

Comparing arrays in C#

Providing that you have LINQ available and don't care too much about performance, the easiest thing is the following:

var arraysAreEqual = Enumerable.SequenceEqual(a1, a2);

In fact, it's probably worth checking with Reflector or ILSpy what the SequenceEqual methods actually does, since it may well optimise for the special case of array values anyway!

How to define an enumerated type (enum) in C?

If you declare the name for enumeration no error will occur.

If not declared, you have to use a typedef:

enum enum_name {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;

It will not display an error...

What is the use of System.in.read()?

It allows you to read from the standard input (mainly, the console). This SO question may helps you.

Getting RAW Soap Data from a Web Reference Client running in ASP.net

I made following changes in web.config to get the SOAP (Request/Response) Envelope. This will output all of the raw SOAP information to the file trace.log.

<system.diagnostics>
  <trace autoflush="true"/>
  <sources>
    <source name="System.Net" maxdatasize="1024">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
    <source name="System.Net.Sockets" maxdatasize="1024">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener"
      initializeData="trace.log"/>
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose"/>
    <add name="System.Net.Sockets" value="Verbose"/>
  </switches>
</system.diagnostics>

How are iloc and loc different?

Label vs. Location

The main distinction between the two methods is:

  • loc gets rows (and/or columns) with particular labels.

  • iloc gets rows (and/or columns) at integer locations.

To demonstrate, consider a series s of characters with a non-monotonic integer index:

>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2]) 
49    a
48    b
47    c
0     d
1     e
2     f

>>> s.loc[0]    # value at index label 0
'd'

>>> s.iloc[0]   # value at index location 0
'a'

>>> s.loc[0:1]  # rows at index labels between 0 and 1 (inclusive)
0    d
1    e

>>> s.iloc[0:1] # rows at index location between 0 and 1 (exclusive)
49    a

Here are some of the differences/similarities between s.loc and s.iloc when passed various objects:

<object> description s.loc[<object>] s.iloc[<object>]
0 single item Value at index label 0 (the string 'd') Value at index location 0 (the string 'a')
0:1 slice Two rows (labels 0 and 1) One row (first row at location 0)
1:47 slice with out-of-bounds end Zero rows (empty Series) Five rows (location 1 onwards)
1:47:-1 slice with negative step Four rows (labels 1 back to 47) Zero rows (empty Series)
[2, 0] integer list Two rows with given labels Two rows with given locations
s > 'e' Bool series (indicating which values have the property) One row (containing 'f') NotImplementedError
(s>'e').values Bool array One row (containing 'f') Same as loc
999 int object not in index KeyError IndexError (out of bounds)
-1 int object not in index KeyError Returns last value in s
lambda x: x.index[3] callable applied to series (here returning 3rd item in index) s.loc[s.index[3]] s.iloc[s.index[3]]

loc's label-querying capabilities extend well-beyond integer indexes and it's worth highlighting a couple of additional examples.

Here's a Series where the index contains string objects:

>>> s2 = pd.Series(s.index, index=s.values)
>>> s2
a    49
b    48
c    47
d     0
e     1
f     2

Since loc is label-based, it can fetch the first value in the Series using s2.loc['a']. It can also slice with non-integer objects:

>>> s2.loc['c':'e']  # all rows lying between 'c' and 'e' (inclusive)
c    47
d     0
e     1

For DateTime indexes, we don't need to pass the exact date/time to fetch by label. For example:

>>> s3 = pd.Series(list('abcde'), pd.date_range('now', periods=5, freq='M')) 
>>> s3
2021-01-31 16:41:31.879768    a
2021-02-28 16:41:31.879768    b
2021-03-31 16:41:31.879768    c
2021-04-30 16:41:31.879768    d
2021-05-31 16:41:31.879768    e

Then to fetch the row(s) for March/April 2021 we only need:

>>> s3.loc['2021-03':'2021-04']
2021-03-31 17:04:30.742316    c
2021-04-30 17:04:30.742316    d

Rows and Columns

loc and iloc work the same way with DataFrames as they do with Series. It's useful to note that both methods can address columns and rows together.

When given a tuple, the first element is used to index the rows and, if it exists, the second element is used to index the columns.

Consider the DataFrame defined below:

>>> import numpy as np 
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),  
                      index=list('abcde'), 
                      columns=['x','y','z', 8, 9])
>>> df
    x   y   z   8   9
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
e  20  21  22  23  24

Then for example:

>>> df.loc['c': , :'z']  # rows 'c' and onwards AND columns up to 'z'
    x   y   z
c  10  11  12
d  15  16  17
e  20  21  22

>>> df.iloc[:, 3]        # all rows, but only the column at index location 3
a     3
b     8
c    13
d    18
e    23

Sometimes we want to mix label and positional indexing methods for the rows and columns, somehow combining the capabilities of loc and iloc.

For example, consider the following DataFrame. How best to slice the rows up to and including 'c' and take the first four columns?

>>> import numpy as np 
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),  
                      index=list('abcde'), 
                      columns=['x','y','z', 8, 9])
>>> df
    x   y   z   8   9
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
e  20  21  22  23  24

We can achieve this result using iloc and the help of another method:

>>> df.iloc[:df.index.get_loc('c') + 1, :4]
    x   y   z   8
a   0   1   2   3
b   5   6   7   8
c  10  11  12  13

get_loc() is an index method meaning "get the position of the label in this index". Note that since slicing with iloc is exclusive of its endpoint, we must add 1 to this value if we want row 'c' as well.

Add data to JSONObject

The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:

JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()

JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);

scrollable div inside container

_x000D_
_x000D_
function start() {_x000D_
 document.getElementById("textBox1").scrollTop +=5;_x000D_
    scrolldelay = setTimeout(function() {start();}, 40);_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
 clearTimeout(scrolldelay);_x000D_
}_x000D_
_x000D_
function reset(){_x000D_
 var loc = document.getElementById("textBox1").scrollTop;_x000D_
 document.getElementById("textBox1").scrollTop -= loc;_x000D_
 clearTimeout(scrolldelay);_x000D_
}_x000D_
//adjust height of paragraph in css_x000D_
//element textbox in div_x000D_
//adjust speed at scrolltop and start 
_x000D_
_x000D_
_x000D_

SQL Query to find the last day of the month

Select DATEADD(DAY, -(DAY(DATEADD(MONTH, 1, GETDATE()))),DATEADD(MONTH, 1, GETDATE()))

This works great in T-sql ..

Replace the GETDATE() of the query with your column name .

After submitting a POST form open a new window showing the result

var urlAction = 'whatever.php';
var data = {param1:'value1'};

var $form = $('<form target="_blank" method="POST" action="' + urlAction + '">');
$.each(data, function(k,v){
    $form.append('<input type="hidden" name="' + k + '" value="' + v + '">');
});
$form.submit();

How to export data from Spark SQL to CSV

The simplest way is to map over the DataFrame's RDD and use mkString:

  df.rdd.map(x=>x.mkString(","))

As of Spark 1.5 (or even before that) df.map(r=>r.mkString(",")) would do the same if you want CSV escaping you can use apache commons lang for that. e.g. here's the code we're using

 def DfToTextFile(path: String,
                   df: DataFrame,
                   delimiter: String = ",",
                   csvEscape: Boolean = true,
                   partitions: Int = 1,
                   compress: Boolean = true,
                   header: Option[String] = None,
                   maxColumnLength: Option[Int] = None) = {

    def trimColumnLength(c: String) = {
      val col = maxColumnLength match {
        case None => c
        case Some(len: Int) => c.take(len)
      }
      if (csvEscape) StringEscapeUtils.escapeCsv(col) else col
    }
    def rowToString(r: Row) = {
      val st = r.mkString("~-~").replaceAll("[\\p{C}|\\uFFFD]", "") //remove control characters
      st.split("~-~").map(trimColumnLength).mkString(delimiter)
    }

    def addHeader(r: RDD[String]) = {
      val rdd = for (h <- header;
                     if partitions == 1; //headers only supported for single partitions
                     tmpRdd = sc.parallelize(Array(h))) yield tmpRdd.union(r).coalesce(1)
      rdd.getOrElse(r)
    }

    val rdd = df.map(rowToString).repartition(partitions)
    val headerRdd = addHeader(rdd)

    if (compress)
      headerRdd.saveAsTextFile(path, classOf[GzipCodec])
    else
      headerRdd.saveAsTextFile(path)
  }

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

[Joke mode on]

You can fix this by adding this:

https://github.com/donavon/undefined-is-a-function

import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.

[joke mode off]

Android image caching

I had been wrestling with this for some time; the answers using SoftReferences would lose their data too quickly. The answers that suggest instantiating a RequestCache were too messy, plus I could never find a full example.

But ImageDownloader.java works wonderfully for me. It uses a HashMap until the capacity is reached or until the purge timeout occurs, then things get moved to a SoftReference, thereby using the best of both worlds.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

This is for my reference, as I encountered a variety of SQL error messages while trying to connect with provider. Other answers prescribe "try this, then this, then this". I appreciate the other answers, but I like to pair specific solutions with specific problems


Error

...provider did not give information...Cannot initialize data source object...

Error Numbers

7399, 7303

Error Detail

Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. 
  The provider did not give any information about the error. 
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object
  of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

File was open. Close it.

Credit


Error

Access denied...Cannot get the column information...

Error Numbers

7399, 7350

Error Detail

Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. 
  Access denied.
Msg 7350, Level 16, State 2, Line 2 Cannot get the column information 
  from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

Give access

Credit


Error

No value given for one or more required parameters....Cannot execute the query ...

Error Numbers

???, 7320

Error Detail

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "No value given for one or more required parameters.".
Msg 7320, Level 16, State 2, Line 2
Cannot execute the query "select [Col A], [Col A] FROM $Sheet" against OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)". 

Solution

Column names might be wrong. Do [Col A] and [Col B] actually exist in your spreadsheet?


Error

"Unspecified error"...Cannot initialize data source object...

Error Numbers

???, 7303

Error Detail

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

Run SSMS as admin. See this question.


Other References

Other answers which suggest modifying properties. Not sure how modifying these two properties (checking them or unchecking them) would help.

Add disabled attribute to input element using Javascript

If you're using jQuery then there are a few different ways to set the disabled attribute.

var $element = $(...);
    $element.prop('disabled', true);
    $element.attr('disabled', true); 

    // The following do not require jQuery
    $element.get(0).disabled = true;
    $element.get(0).setAttribute('disabled', true);
    $element[0].disabled = true;
    $element[0].setAttribute('disabled', true);

How to get ip address of a server on Centos 7 in bash

You can run simple commands like

curl ifconfig.co

curl ifconfig.me

wget -qO - icanhazip.com

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

Just wanted to say that this answer is brilliant and I'm using it for a long time without problems. But some time ago I've stumbled upon a problem that DownloadsProvider returns URIs in format content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Fdoc.pdf and hence app is crashed with NumberFormatException as it's impossible to parse its uri segments as long. But raw: segment contains direct uri which can be used to retrieve a referenced file. So I've fixed it by replacing isDownloadsDocument(uri) if content with following:

final String id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
    return id.replaceFirst("raw:", "");
}
try {
    final Uri contentUri = ContentUris.withAppendedId(
            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
    return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
    Log.e("FileUtils", "Downloads provider returned unexpected uri " + uri.toString(), e);
    return null;
}
}

Which exception should I raise on bad/illegal argument combinations in Python?

I've mostly just seen the builtin ValueError used in this situation.

Rails: Adding an index after adding column

Add in the generated migration after creating the column the following (example)

add_index :photographers, :email, :unique => true

Detect change to selected date with bootstrap-datepicker

You can use onSelect event

 $("#date-daily").datepicker({
  onSelect: function(dateText) {
   alert($('#dp3').val());
  }
});

It is Called when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters. this refers to the associated input field.

SEE HERE

How to use http.client in Node.js if there is basic authorization

var username = "Ali";
var password = "123";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
var url = "http://localhost:5647/contact/session/";

request.get( {
    url : url,
    headers : {
        "Authorization" : auth
    }
  }, function(error, response, body) {
      console.log('body : ', body);
  } );

How to check if a registry value exists using C#?

public bool ValueExists(RegistryKey Key, string Value)
{
   try
   {
       return Key.GetValue(Value) != null;
   }
   catch
   {
       return false;
   }
}

This simple function will return true only if a value is found but it is not null, else will return false if the value exists but it is null or the value doesn't exists in the key.


USAGE for your question:

if (ValueExists(winLogonKey, "Start")
{
    // The values exists
}
else
{
    // The values does not exists
}

Java: Date from unix timestamp

This is the right way:

Date date = new Date ();
date.setTime((long)unix_time*1000);

Inner text shadow with CSS

text-shadow: 4px 4px 2px rgba(150, 150, 150, 1);

for box shadow:

-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
-moz-box-shadow:    7px 7px 5px rgba(50, 50, 50, 0.75);
box-shadow:         7px 7px 5px rgba(50, 50, 50, 0.75);

you can see online text and box shadow: online text and box shadow

for more example you can go to this address : more example code freeclup

C++ Erase vector element by value rather than by position?

How about std::remove() instead:

#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());

This combination is also known as the erase-remove idiom.

Adding a slide effect to bootstrap dropdown

$('.navbar .dropdown').hover(function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
}, function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});

This code works if you want to reveal dropdowns on hover.

I just changed the .slideToggle to .slideDown & .slideUp, and removed the (400) timing

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.

This code works as expected (I just changed the type from double to String):

public static void main(String[] args) {
  String doubleVal = "1.745";
  String doubleVal1 = "0.745";
  BigDecimal bdTest = new BigDecimal(  doubleVal);
  BigDecimal bdTest1 = new BigDecimal(  doubleVal1 );
  bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
  bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
  System.out.println("bdTest:"+bdTest); //1.75
  System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}

A potentially dangerous Request.Path value was detected from the client (*)

You should encode the route value and then (if required) decode the value before searching.

How to set JFrame to appear centered, regardless of monitor resolution?

I am using NetBeans IDE 7.3 and this is how I go about centralizing my JFrame Make sure you click on the JFrame Panel and go to your JFrame property bar,click on the Code bar and select Generate Center check box.

Why is my Git Submodule HEAD detached from master?

EDIT:

See @Simba Answer for valid solution

submodule.<name>.update is what you want to change, see the docs - default checkout
submodule.<name>.branch specify remote branch to be tracked - default master


OLD ANSWER:

Personally I hate answers here which direct to external links which may stop working over time and check my answer here (Unless question is duplicate) - directing to question which does cover subject between the lines of other subject, but overall equals: "I'm not answering, read the documentation."

So back to the question: Why does it happen?

Situation you described

After pulling changes from server, many times my submodule head gets detached from master branch.

This is a common case when one does not use submodules too often or has just started with submodules. I believe that I am correct in stating, that we all have been there at some point where our submodule's HEAD gets detached.

  • Cause: Your submodule is not tracking correct branch (default master).
    Solution: Make sure your submodule is tracking the correct branch
$ cd <submodule-path>
# if the master branch already exists locally:
# (From git docs - branch)
# -u <upstream>
# --set-upstream-to=<upstream>
#    Set up <branchname>'s tracking information so <upstream>
#    is considered <branchname>'s upstream branch.
#    If no <branchname> is specified, then it defaults to the current branch.
$ git branch -u <origin>/<branch> <branch>
# else:
$ git checkout -b <branch> --track <origin>/<branch>
  • Cause: Your parent repo is not configured to track submodules branch.
    Solution: Make your submodule track its remote branch by adding new submodules with the following two commands.
    • First you tell git to track your remote <branch>.
    • you tell git to perform rebase or merge instead of checkout
    • you tell git to update your submodule from remote.
    $ git submodule add -b <branch> <repository> [<submodule-path>]
    $ git config -f .gitmodules submodule.<submodule-path>.update rebase
    $ git submodule update --remote
  • If you haven't added your existing submodule like this you can easily fix that:
    • First you want to make sure that your submodule has the branch checked out which you want to be tracked.
    $ cd <submodule-path>
    $ git checkout <branch>
    $ cd <parent-repo-path>
    # <submodule-path> is here path releative to parent repo root
    # without starting path separator
    $ git config -f .gitmodules submodule.<submodule-path>.branch <branch>
    $ git config -f .gitmodules submodule.<submodule-path>.update <rebase|merge>

In the common cases, you already have fixed by now your DETACHED HEAD since it was related to one of the configuration issues above.

fixing DETACHED HEAD when .update = checkout

$ cd <submodule-path> # and make modification to your submodule
$ git add .
$ git commit -m"Your modification" # Let's say you forgot to push it to remote.
$ cd <parent-repo-path>
$ git status # you will get
Your branch is up-to-date with '<origin>/<branch>'.
Changes not staged for commit:
    modified:   path/to/submodule (new commits)
# As normally you would commit new commit hash to your parent repo
$ git add -A
$ git commit -m"Updated submodule"
$ git push <origin> <branch>.
$ git status
Your branch is up-to-date with '<origin>/<branch>'.
nothing to commit, working directory clean
# If you now update your submodule
$ git submodule update --remote
Submodule path 'path/to/submodule': checked out 'commit-hash'
$ git status # will show again that (submodule has new commits)
$ cd <submodule-path>
$ git status
HEAD detached at <hash>
# as you see you are DETACHED and you are lucky if you found out now
# since at this point you just asked git to update your submodule
# from remote master which is 1 commit behind your local branch
# since you did not push you submodule chage commit to remote. 
# Here you can fix it simply by. (in submodules path)
$ git checkout <branch>
$ git push <origin>/<branch>
# which will fix the states for both submodule and parent since 
# you told already parent repo which is the submodules commit hash 
# to track so you don't see it anymore as untracked.

But if you managed to make some changes locally already for submodule and commited, pushed these to remote then when you executed 'git checkout ', Git notifies you:

$ git checkout <branch>
Warning: you are leaving 1 commit behind, not connected to any of your branches:
If you want to keep it by creating a new branch, this may be a good time to do so with:

The recommended option to create a temporary branch can be good, and then you can just merge these branches etc. However I personally would use just git cherry-pick <hash> in this case.

$ git cherry-pick <hash> # hash which git showed you related to DETACHED HEAD
# if you get 'error: could not apply...' run mergetool and fix conflicts
$ git mergetool
$ git status # since your modifications are staged just remove untracked junk files
$ rm -rf <untracked junk file(s)>
$ git commit # without arguments
# which should open for you commit message from DETACHED HEAD
# just save it or modify the message.
$ git push <origin> <branch>
$ cd <parent-repo-path>
$ git add -A # or just the unstaged submodule
$ git commit -m"Updated <submodule>"
$ git push <origin> <branch>

Although there are some more cases you can get your submodules into DETACHED HEAD state, I hope that you understand now a bit more how to debug your particular case.

Set selected radio from radio group with a value

Pure JavaScript version:

document.querySelector('input[name="myradio"][value="5"]').checked = true;

How to keep the spaces at the end and/or at the beginning of a String?

All answers here did not work for me. Instead, to add a space at the end of a string in XML i did this

<string name="more_store">more store<b> </b> </string>

How to check if a String contains any letter from a to z?

You could use RegEx:

Regex.IsMatch(hello, @"^[a-zA-Z]+$");

If you don't like that, you can use LINQ:

hello.All(Char.IsLetter);

Or, you can loop through the characters, and use isAlpha:

Char.IsLetter(character);

How to get character array from a string?

As hippietrail suggests, meder's answer can break surrogate pairs and misinterpret “characters.” For example:

_x000D_
_x000D_
// DO NOT USE THIS!
const a = ''.split('');
console.log(a);
_x000D_
_x000D_
_x000D_

I suggest using one of the following ES2015 features to correctly handle these character sequences.

Spread syntax (already answered by insertusernamehere)

_x000D_
_x000D_
const a = [...''];
console.log(a);
_x000D_
_x000D_
_x000D_

Array.from

_x000D_
_x000D_
const a = Array.from('');
console.log(a);
_x000D_
_x000D_
_x000D_

RegExp u flag

_x000D_
_x000D_
const a = ''.split(/(?=[\s\S])/u);
console.log(a);
_x000D_
_x000D_
_x000D_

Use /(?=[\s\S])/u instead of /(?=.)/u because . does not match newlines. If you are still in ES5.1 era (or if your browser doesn't handle this regex correctly - like Edge), you can use the following alternative (transpiled by Babel). Note, that Babel tries to also handle unmatched surrogates correctly. However, this doesn't seem to work for unmatched low surrogates.

_x000D_
_x000D_
const a = ''.split(/(?=(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/);
console.log(a);
_x000D_
_x000D_
_x000D_

Reduce method (already answered by Mark Amery)

_x000D_
_x000D_
const s = '';
const a = [];
for (const s2 of s) {
   a.push(s2);
}
console.log(a);
_x000D_
_x000D_
_x000D_

How to sort an array of ints using a custom comparator?

How about using streams (Java 8)?

int[] ia = {99, 11, 7, 21, 4, 2};
ia = Arrays.stream(ia).
    boxed().
    sorted((a, b) -> b.compareTo(a)). // sort descending
    mapToInt(i -> i).
    toArray();

Or in-place:

int[] ia = {99, 11, 7, 21, 4, 2};
System.arraycopy(
        Arrays.stream(ia).
            boxed().
            sorted((a, b) -> b.compareTo(a)). // sort descending
            mapToInt(i -> i).
            toArray(),
        0,
        ia,
        0,
        ia.length
    );

Pass parameter to controller from @Html.ActionLink MVC 4

I have to pass two parameters like:

/Controller/Action/Param1Value/Param2Value

This way:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= Param1Value, 
        Param2Name = Param2Value 
    },
    htmlAttributes: null
)

will generate this url

/Controller/Action/Param1Value?Param2Name=Param2Value

I used a workaround method by merging parameter two in parameter one and I get what I wanted:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= "Param1Value / Param2Value" ,      
    },
    htmlAttributes: null
)

And I get :

/Controller/Action/Param1Value/Param2Value

How to remove new line characters from a string?

You want to use String.Replace to remove a character.

s = s.Replace("\n", String.Empty);
s = s.Replace("\r", String.Empty);
s = s.Replace("\t", String.Empty);

Note that String.Trim(params char[] trimChars) only removes leading and trailing characters in trimChars from the instance invoked on.

You could make an extension method, which avoids the performance problems of the above of making lots of temporary strings:

static string RemoveChars(this string s, params char[] removeChars) {
    Contract.Requires<ArgumentNullException>(s != null);
    Contract.Requires<ArgumentNullException>(removeChars != null);
    var sb = new StringBuilder(s.Length);
    foreach(char c in s) { 
        if(!removeChars.Contains(c)) {
            sb.Append(c);
        }
    }
    return sb.ToString();
}

Adding image inside table cell in HTML

Or... You could place the image in an anchor tag. Cause I had the same problem and it fixed it without issue. A lot of people use local paths before they publish their site and photos. Just make sure you go back and fix that in the final editing phase.

Make an image width 100% of parent div, but not bigger than its own width

I would use the property display: table-cell

Here is the link

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

Styling Google Maps InfoWindow

I used the following code to apply some external CSS:

boxText = document.createElement("html");
boxText.innerHTML = "<head><link rel='stylesheet' href='style.css'/></head><body>[some html]<body>";

infowindow.setContent(boxText);
infowindow.open(map, marker);

Inherit CSS class

You could also use the !important feature of css to make qualities you do not want to override in the original class. I am using this on my site to keep some of the essential characteristics of the original class while overriding others:

<div class="foo bar">
.foo {
color: blue;
width: 200px  !important;
}

.bar {
color: red;
width: 400px;
}

This will generate a class "foo bar" element that is red and 200px. This is great if you are using the other two classes individually and just want a piece from each class.

How do you divide each element in a list by an int?

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [i/myInt for i in myList]

Capturing a single image from my webcam in Java or Python

Some time ago I wrote simple Webcam Capture API which can be used for that. The project is available on Github.

Example code:

Webcam webcam = Webcam.getDefault();
webcam.open();
try {
  ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
} catch (IOException e) {
  e.printStackTrace();
} finally {
  webcam.close();
}

What are enums and why are they useful?

So far, I have never needed to use enums. I have been reading about them since they were introduced in 1.5 or version tiger as it was called back in the day. They never really solved a 'problem' for me. For those who use it (and I see a lot of them do), am sure it definitely serves some purpose. Just my 2 quid.

Copying a local file from Windows to a remote server using scp

I have found it easiest to use a graphical interface on windows (I recommend mobaXTerm it has ssh, scp, ftp, remote desktop, and many more) but if you are set on command line I would recommend cd'ing into the directory with the source folder then
scp -r yourFolder username@server:/path/to/dir
the -r indicates recursive to be used on directories

Switch case with fallthrough?

Recent bash versions allow fall-through by using ;& in stead of ;;: they also allow resuming the case checks by using ;;& there.

for n in 4 14 24 34
do
  echo -n "$n = "
  case "$n" in
   3? )
     echo -n thirty-
     ;;&   #resume (to find ?4 later )
   "24" )
     echo -n twenty-
     ;&   #fallthru
   "4" | [13]4)
     echo -n four 
     ;;&  # resume ( to find teen where needed )
   "14" )
     echo -n teen
  esac
  echo 
done

sample output

4 = four
14 = fourteen
24 = twenty-four
34 = thirty-four

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

<div ng-repeat="subject in results.subjects | filter:{grade:'C'}">
    <input ng-model="subject.title" />
</div>

Imitating a blink tag with CSS3 animations

If you want smooth blinking text or something a like you can use following code:

_x000D_
_x000D_
 .blinking {
    -webkit-animation: 1s blink ease infinite;
    -moz-animation: 1s blink ease infinite;
    -ms-animation: 1s blink ease infinite;
    -o-animation: 1s blink ease infinite;
    animation: 1s blink ease infinite;
  }

  @keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-moz-keyframes blink {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-webkit-keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-ms-keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }

  @-o-keyframes "blink" {

    from,
    to {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }
_x000D_
<span class="blinking">I am smoothly blinking</span>
_x000D_
_x000D_
_x000D_

How can I find the current OS in Python?

If you want user readable data but still detailed, you can use platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

platform also has some other useful methods:

>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'

Here's a few different possible calls you can make to identify where you are

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

e.g. Solaris on sparc gave:

Python version: ['2.6.4 (r264:75706, Aug  4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')

getting the ng-object selected with ng-change

If Divyesh Rupawala's answer doesn't work (passing the current item as the parameter), then please see the onChanged() function in this Plunker. It's using this:

http://plnkr.co/edit/B5TDQJ

How to install Anaconda on RaspBerry Pi 3 Model B

I was trying to run this on a pi zero. Turns out the pi zero has an armv6l architecture so the above won't work for pi zero or pi one. Alternatively here I learned that miniconda doesn't have a recent version of miniconda. Instead I used the same instructions posted here to install berryconda3

Conda is now working. Hope this helps those of you interested in running conda on the pi zero!

Animate scroll to ID on page load

Pure javascript solution with scrollIntoView() function:

_x000D_
_x000D_
document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
_x000D_
<h2 id="title1">Some title</h2>
_x000D_
_x000D_
_x000D_

P.S. 'smooth' parameter now works from Chrome 61 as julien_c mentioned in the comments.

NPM doesn't install module dependencies

I had the same problem. But on the same machine one project had good package.json, where all my dependencies are successfully installed. And in another project my package.json dependencies were not installed no matter what i do. I just copied the package.json and pasted into that another project. And it worked! The difference i have found was only empty line at the start of file. Dont know or it influences anything, maybe some other problem. But the problem was only the package.json file.

MySQL: is a SELECT statement case sensitive?

They are case insensitive, unless you do a binary comparison.

Angular 2 @ViewChild annotation returns undefined

My solution to this was to replace *ngIf with [hidden]. Downside was all the child components were present in the code DOM. But worked for my requirements.

SOAP PHP fault parsing WSDL: failed to load external entity?

If you use docker there is a chance you get error because of OpenSSL default security level.

You need lower seclevel in /etc/ssl/openssl.cnf from DEFAULT@SECLEVEL=2 to DEFAULT@SECLEVEL=1

Or just add into Dockerfile

RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf

Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876

After that change I can run SoapClient without any additional options


You can verify it by run on container

curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl

Is it possible to use JS to open an HTML select to show its option list?

Unfortunately there's a simple answer to this question, and it's "No"

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

I solved it with my own function. If you want to update specified field in document you need to address it clearly.

Example:

{
    _id : ...,
    some_key: { 
        param1 : "val1",
        param2 : "val2",
        param3 : "val3"
    }
}

If you want to update param2 only, it's wrong to do:

db.collection.update(  { _id:...} , { $set: { some_key : new_info  } }  //WRONG

You must use:

db.collection.update(  { _id:...} , { $set: { some_key.param2 : new_info  } } 

So i wrote a function something like that:

function _update($id, $data, $options=array()){

    $temp = array();
    foreach($data as $key => $value)
    {
        $temp["some_key.".$key] = $value;
    } 

    $collection->update(
        array('_id' => $id),
        array('$set' => $temp)
    );

}

_update('1', array('param2' => 'some data'));

Force IE9 to emulate IE8. Possible?

The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.

What is mapDispatchToProps?

It's basically a shorthand. So instead of having to write:

this.props.dispatch(toggleTodo(id));

You would use mapDispatchToProps as shown in your example code, and then elsewhere write:

this.props.onTodoClick(id);

or more likely in this case, you'd have that as the event handler:

<MyComponent onClick={this.props.onTodoClick} />

There's a helpful video by Dan Abramov on this here: https://egghead.io/lessons/javascript-redux-generating-containers-with-connect-from-react-redux-visibletodolist

How to get bitmap from a url in android?

Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:

File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);

getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.

Under what conditions is a JSESSIONID created?

JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want to get the session, but not create it if it doesn't exist, use request.getSession(false) -- this will return you a session or null. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that session isn't necessarily created on first request... you and your code are in control when the session is created)

Sessions are per-context:

SRV.7.3 Session Scope

HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.

(Servlet 2.4 specification)

Update: Every call to JSP page implicitly creates a new session if there is no session yet. This can be turned off with the session='false' page directive, in which case session variable is not available on JSP page at all.

Length of a JavaScript object

Simple solution:

  var myObject = {};      // ... your object goes here.

  var length = 0;

  for (var property in myObject) {
    if (myObject.hasOwnProperty(property)){
      length += 1;
    }
  };

  console.log(length);    // logs 0 in my example.

How to set CATALINA_HOME variable in windows 7?

Assuming Java (JDK + JRE) is installed in your system, do the following:

  1. Install Tomcat7
  2. Copy 'tools.jar' from 'C:\Program Files (x86)\Java\jdk1.6.0_27\lib' and pasted it under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib'.
  3. Setup paths in your Environment Variables as shown below:

C:/>javap javax.servlet.http.HttpServletRequest

It should show a bunch of classes

How to use if statements in LESS

I wrote a mixin for some syntactic sugar ;)
Maybe someone likes this way of writing if-then-else better than using guards

depends on Less 1.7.0

https://github.com/pixelass/more-or-less/blob/master/less/fn/_if.less

Usage:

.if(isnumber(2), {
    .-then(){
        log {
            isnumber: true;
        }
    }
    .-else(){
        log {
            isnumber: false;
        }
    }
});

.if(lightness(#fff) gt (20% * 2), {
    .-then(){
        log {
            is-light: true;
        }
    }
});

using on example from above

.if(@debug, {
    .-then(){
        header {
            background-color: yellow;
            #title {
                background-color: orange;
            }
        }
        article {
            background-color: red;
        }
    }
});

Git on Windows: How do you set up a mergetool?

For IntelliJ IDEA (Community Edition) 3-way git mergetool configuration in Windows environment (~/.gitconfig)

Cygwin

[mergetool "ideamerge"]
     cmd = C:/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe merge `cygpath -wa $LOCAL` `cygpath -wa $REMOTE` `cygpath -wa $BASE` `cygpath -wa $MERGED`
[merge]
     tool = ideamerge

Msys

[mergetool "ideamerge"]
cmd = "/c/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe" merge `~/winpath.sh $LOCAL` `~/winpath.sh $REMOTE` `~/winpath.sh $BASE` `~/winpath.sh $MERGED`
[merge]
 tool = ideamerge

The ~/winpath.sh is to convert paths to Windows on msys and is taken from msys path conversion question on stackoverflow

#! /bin/sh                                                               

function wpath {                                                         
    if [ -z "$1" ]; then                                                 
        echo "$@"                                                        
    else                                                                 
        if [ -f "$1" ]; then                                             
            local dir=$(dirname "$1")                                    
            local fn=$(basename "$1")                                    
            echo "$(cd "$dir"; echo "$(pwd -W)/$fn")" | sed 's|/|\\|g';  
        else                                                             
            if [ -d "$1" ]; then                                         
                echo "$(cd "$1"; pwd -W)" | sed 's|/|\\|g';              
            else                                                         
                echo "$1" | sed 's|^/\(.\)/|\1:\\|g; s|/|\\|g';          
            fi                                                           
        fi                                                               
    fi                                                                   
}                                                                        

wpath "$@" 

add Shadow on UIView using swift 3

CODE SNIPPET:

extension UIView {

  // OUTPUT 1
  func dropShadow(scale: Bool = true) {
    layer.masksToBounds = false
    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOpacity = 0.5
    layer.shadowOffset = CGSize(width: -1, height: 1)
    layer.shadowRadius = 1

    layer.shadowPath = UIBezierPath(rect: bounds).cgPath
    layer.shouldRasterize = true
    layer.rasterizationScale = scale ? UIScreen.main.scale : 1
  }

  // OUTPUT 2
  func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
    layer.masksToBounds = false
    layer.shadowColor = color.cgColor
    layer.shadowOpacity = opacity
    layer.shadowOffset = offSet
    layer.shadowRadius = radius

    layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
    layer.shouldRasterize = true
    layer.rasterizationScale = scale ? UIScreen.main.scale : 1
  }
}

NOTE: If you don't pass any parameter to that function, then the scale argument will be true by default. You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.

OUTPUT 1:

shadowView.dropShadow()

enter image description here

OUTPUT 2:

shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)

enter image description here

layer.shouldRasterize = true will make the shadow static and cause a shadow for the initial state of the UIView. So I would recommend not to use layer.shouldRasterize = true in dynamic layouts like view inside a UITableViewCell.

Ansible: get current target host's IP address

Just use ansible_ssh_host variable

playbook_example.yml

- hosts: host1
  tasks:
  - name: Show host's ip
    debug:
      msg: "{{ ansible_ssh_host }}"

hosts.yml

[hosts]
host1   ansible_host=1.2.3.4

Result

TASK [Show host's ip] *********************************************************************************************************************************************************************************************
ok: [host1] => {
     "msg": "1.2.3.4"
}

How to add an element to the beginning of an OrderedDict?

If you know you will want a 'c' key, but do not know the value, insert 'c' with a dummy value when you create the dict.

d1 = OrderedDict([('c', None), ('a', '1'), ('b', '2')])

and change the value later.

d1['c'] = 3

Protect image download

There is no way to protect image downloading. This is because the image has to be downloaded by the browser for it to be seen by the user. There are tricks (like the transparent background you specified) to restrict certain operations like image right click and saving to browser cache folder, but there isn't a way for truly protecting the images.

What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki


Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.


gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

NSRange to Range<String.Index>

extension StringProtocol where Index == String.Index {

    func nsRange(of string: String) -> NSRange? {
        guard let range = self.range(of: string) else {  return nil }
        return NSRange(range, in: self)
    }
}

How to export dataGridView data Instantly to Excel on button click?

In my opinion this is the easiest and instantly working method of exporting datagridview.

 try
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel Documents (*.xlsx)|*.xlsx";
            sfd.FileName = "ProfitLoss.xlsx";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                DataTable dts = new DataTable();
                for (int i = 0; i < grdProfitAndLoss.Columns.Count; i++)
                {
                    dts.Columns.Add(grdProfitAndLoss.Columns[i].Name);
                }
                for (int j = 0; j < grdProfitAndLoss.Rows.Count; j++)
                {
                    DataRow toInsert = dts.NewRow();
                    int k = 0;
                    int inc = 0;
                    for (k = 0; k < grdProfitAndLoss.Columns.Count; k++)
                    {
                        if (grdProfitAndLoss.Columns[k].Visible == false) { continue; }
                        toInsert[inc] = grdProfitAndLoss.Rows[j].Cells[k].Value;
                        inc++;
                    }
                    dts.Rows.Add(toInsert);
                }
                dts.AcceptChanges();
                ExcelUtlity obj = new ExcelUtlity();
                obj.WriteDataTableToExcel(dts, "Profit And Loss", sfd.FileName, "Profit And Loss");
                MessageBox.Show("Exported Successfully");
            }
        }
        catch (Exception ex)
        {

        }

What is a web service endpoint?

A web service endpoint is the URL that another program would use to communicate with your program. To see the WSDL you add ?wsdl to the web service endpoint URL.

Web services are for program-to-program interaction, while web pages are for program-to-human interaction.

So: Endpoint is: http://www.blah.com/myproject/webservice/webmethod

Therefore, WSDL is: http://www.blah.com/myproject/webservice/webmethod?wsdl


To expand further on the elements of a WSDL, I always find it helpful to compare them to code:

A WSDL has 2 portions (physical & abstract).

Physical Portion:

Definitions - variables - ex: myVar, x, y, etc.

Types - data types - ex: int, double, String, myObjectType

Operations - methods/functions - ex: myMethod(), myFunction(), etc.

Messages - method/function input parameters & return types

  • ex: public myObjectType myMethod(String myVar)

Porttypes - classes (i.e. they are a container for operations) - ex: MyClass{}, etc.

Abstract Portion:

Binding - these connect to the porttypes and define the chosen protocol for communicating with this web service. - a protocol is a form of communication (so text/SMS, vs. phone vs. email, etc.).

Service - this lists the address where another program can find your web service (i.e. your endpoint).

Google Maps API v3 adding an InfoWindow to each marker

In My case (Using Javascript insidde Razor) This worked perfectly inside an Foreach loop

google.maps.event.addListener(marker, 'click', function() {
    marker.info.open(map, this);
});

Render HTML string as real HTML in a React component

dangerouslySetInnerHTML

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

c# - How to get sum of the values from List?

You can use the Sum function, but you'll have to convert the strings to integers, like so:

int total = monValues.Sum(x => Convert.ToInt32(x));

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

How do I write a for loop in bash

I commonly like to use a slight variant on the standard for loop. I often use this to run a command on a series of remote hosts. I take advantage of bash's brace expansion to create for loops that allow me to create non-numerical for-loops.

Example:

I want to run the uptime command on frontend hosts 1-5 and backend hosts 1-3:

% for host in {frontend{1..5},backend{1..3}}.mycompany.com
    do ssh $host "echo -n $host; uptime"
  done

I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. pre{foo,bar}post results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z etc.). However, the double period syntax is a new feature of bash 3.0; earlier versions will not support this.

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

How do I add the contents of an iterable to a set?

You can use the set() function to convert an iterable into a set, and then use standard set update operator (|=) to add the unique values from your new set into the existing one.

>>> a = { 1, 2, 3 }
>>> b = ( 3, 4, 5 )
>>> a |= set(b)
>>> a
set([1, 2, 3, 4, 5])

Declare an empty two-dimensional array in Javascript?

You can nest one array within another using the shorthand syntax:

   var twoDee = [[]];

Get ASCII value at input word

char (with a lower-case c) is a numeric type. It already holds the ascii value of the char. Just cast it to an integer to display it as a numeric value rather than a textual value:

System.out.println("char " + ch + " has the following value : " + (int) ch);

MySQL order by before group by

What you are going to read is rather hacky, so don't try this at home!

In SQL in general the answer to your question is NO, but because of the relaxed mode of the GROUP BY (mentioned by @bluefeet), the answer is YES in MySQL.

Suppose, you have a BTREE index on (post_status, post_type, post_author, post_date). How does the index look like under the hood?

(post_status='publish', post_type='post', post_author='user A', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user A', post_date='2012-12-31') (post_status='publish', post_type='post', post_author='user B', post_date='2012-10-01') (post_status='publish', post_type='post', post_author='user B', post_date='2012-12-01')

That is data is sorted by all those fields in ascending order.

When you are doing a GROUP BY by default it sorts data by the grouping field (post_author, in our case; post_status, post_type are required by the WHERE clause) and if there is a matching index, it takes data for each first record in ascending order. That is the query will fetch the following (the first post for each user):

(post_status='publish', post_type='post', post_author='user A', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user B', post_date='2012-10-01')

But GROUP BY in MySQL allows you to specify the order explicitly. And when you request post_user in descending order, it will walk through our index in the opposite order, still taking the first record for each group which is actually last.

That is

...
WHERE wp_posts.post_status='publish' AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author DESC

will give us

(post_status='publish', post_type='post', post_author='user B', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user A', post_date='2012-12-31')

Now, when you order the results of the grouping by post_date, you get the data you wanted.

SELECT wp_posts.*
FROM wp_posts
WHERE wp_posts.post_status='publish' AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author DESC
ORDER BY wp_posts.post_date DESC;

NB:

This is not what I would recommend for this particular query. In this case, I would use a slightly modified version of what @bluefeet suggests. But this technique might be very useful. Take a look at my answer here: Retrieving the last record in each group

Pitfalls: The disadvantages of the approach is that

  • the result of the query depends on the index, which is against the spirit of the SQL (indexes should only speed up queries);
  • index does not know anything about its influence on the query (you or someone else in future might find the index too resource-consuming and change it somehow, breaking the query results, not only its performance)
  • if you do not understand how the query works, most probably you'll forget the explanation in a month and the query will confuse you and your colleagues.

The advantage is performance in hard cases. In this case, the performance of the query should be the same as in @bluefeet's query, because of amount of data involved in sorting (all data is loaded into a temporary table and then sorted; btw, his query requires the (post_status, post_type, post_author, post_date) index as well).

What I would suggest:

As I said, those queries make MySQL waste time sorting potentially huge amounts of data in a temporary table. In case you need paging (that is LIMIT is involved) most of the data is even thrown off. What I would do is minimize the amount of sorted data: that is sort and limit a minimum of data in the subquery and then join back to the whole table.

SELECT * 
FROM wp_posts
INNER JOIN
(
  SELECT max(post_date) post_date, post_author
  FROM wp_posts
  WHERE post_status='publish' AND post_type='post'
  GROUP BY post_author
  ORDER BY post_date DESC
  -- LIMIT GOES HERE
) p2 USING (post_author, post_date)
WHERE post_status='publish' AND post_type='post';

The same query using the approach described above:

SELECT *
FROM (
  SELECT post_id
  FROM wp_posts
  WHERE post_status='publish' AND post_type='post'
  GROUP BY post_author DESC
  ORDER BY post_date DESC
  -- LIMIT GOES HERE
) as ids
JOIN wp_posts USING (post_id);

All those queries with their execution plans on SQLFiddle.

CAST DECIMAL to INT

There's also ROUND() if your numbers don't necessarily always end with .00. ROUND(20.6) will give 21, and ROUND(20.4) will give 20.

Failed to find Build Tools revision 23.0.1

I had this error:

Failed to find Build Tools revision 23.0.2

When you got updated/installed:

  1. Android SDK Build Tools
  2. Android SDK Tools

Change version number in build.gradle

FROM

buildToolsVersion "23.0.2"

TO

buildToolsVersion "25.0.2"

How to find what Build Tools version you have

Postgres: INSERT if does not exist already

How can I write an 'INSERT unless this row already exists' SQL statement?

There is a nice way of doing conditional INSERT in PostgreSQL:

INSERT INTO example_table
    (id, name)
SELECT 1, 'John'
WHERE
    NOT EXISTS (
        SELECT id FROM example_table WHERE id = 1
    );

CAVEAT This approach is not 100% reliable for concurrent write operations, though. There is a very tiny race condition between the SELECT in the NOT EXISTS anti-semi-join and the INSERT itself. It can fail under such conditions.

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

Make sure all your tables have one primary key. I forgot to add a primary key to one table and that solved this problem for me. :)

Set opacity of background image without affecting child elements

This will work with every browser

div {
 -khtml-opacity:.50; 
 -moz-opacity:.50; 
 -ms-filter:"alpha(opacity=50)";
  filter:alpha(opacity=50);
  filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
  opacity:.50; 
}

If you don't want transparency to affect the entire container and its children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent.

Check demo at http://www.impressivewebs.com/css-opacity-that-doesnt-affect-child-elements/

How to close form

You need the actual instance of the WindowSettings that's open, not a new one.

Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn't do anything because that new instance never has been shown.

Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.

Something like this:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel();
    dialogSettingsCancel.OwningWindowSettings = this;
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

public WindowSettings OwningWindowSettings { get; set; }

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    if(OwningWindowSettings != null)
        OwningWindowSettings.Close();
}

This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.

If the two are always connected, you should instead use a constructor parameter:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel(this);
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

WindowSettings _owningWindowSettings;

public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
    if(owningWindowSettings == null)
        throw new ArgumentNullException("owningWindowSettings");

    _owningWindowSettings = owningWindowSettings;
}

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    _owningWindowSettings.Close();
}

How to get the current time in milliseconds from C in Linux?

This version need not math library and checked the return value of clock_gettime().

#include <time.h>
#include <stdlib.h>
#include <stdint.h>

/**
 * @return milliseconds
 */
uint64_t get_now_time() {
  struct timespec spec;
  if (clock_gettime(1, &spec) == -1) { /* 1 is CLOCK_MONOTONIC */
    abort();
  }

  return spec.tv_sec * 1000 + spec.tv_nsec / 1e6;
}

Multiple Inheritance in C#

Consider just using composition instead of trying to simulate Multiple Inheritance. You can use Interfaces to define what classes make up the composition, eg: ISteerable implies a property of type SteeringWheel, IBrakable implies a property of type BrakePedal, etc.

Once you've done that, you could use the Extension Methods feature added to C# 3.0 to further simplify calling methods on those implied properties, eg:

public interface ISteerable { SteeringWheel wheel { get; set; } }

public interface IBrakable { BrakePedal brake { get; set; } }

public class Vehicle : ISteerable, IBrakable
{
    public SteeringWheel wheel { get; set; }

    public BrakePedal brake { get; set; }

    public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }
}

public static class SteeringExtensions
{
    public static void SteerLeft(this ISteerable vehicle)
    {
        vehicle.wheel.SteerLeft();
    }
}

public static class BrakeExtensions
{
    public static void Stop(this IBrakable vehicle)
    {
        vehicle.brake.ApplyUntilStop();
    }
}


public class Main
{
    Vehicle myCar = new Vehicle();

    public void main()
    {
        myCar.SteerLeft();
        myCar.Stop();
    }
}

How to create a pulse effect using -webkit-animation - outward rings

You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.

Here is a solution that cleans up a lot of code and makes the animation start from the center:

.gps_ring {
    border: 3px solid #999;
    -webkit-border-radius: 30px;
    height: 18px;
    width: 18px;
    position: absolute;
    left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

You can see it in action here: http://jsfiddle.net/Fy8vD/

Using OpenSSL what does "unable to write 'random state'" mean?

I know this question is on Linux, but on windows I had the same issue. Turns out you have to start the command prompt in "Run As Administrator" mode for it to work. Otherwise you get the same: unable to write 'random state' error.

How to write "not in ()" sql query using join

SELECT d1.Short_Code 
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL

What is the difference between new/delete and malloc/free?

new calls the ctor of the object, delete call the dtor.

malloc & free just allocate and release raw memory.

C++11 thread-safe queue

This is probably how you should do it:

void push(std::string&& filename)
{
    {
        std::lock_guard<std::mutex> lock(qMutex);

        q.push(std::move(filename));
    }

    populatedNotifier.notify_one();
}

bool try_pop(std::string& filename, std::chrono::milliseconds timeout)
{
    std::unique_lock<std::mutex> lock(qMutex);

    if(!populatedNotifier.wait_for(lock, timeout, [this] { return !q.empty(); }))
        return false;

    filename = std::move(q.front());
    q.pop();

    return true;    
}

How to download and save a file from Internet using Java?

There is method U.fetch(url) in underscore-java library.

pom.xml:

  <groupId>com.github.javadev</groupId>
  <artifactId>underscore</artifactId>
  <version>1.45</version>

Code example:

import com.github.underscore.lodash.U;

public class Download {
    public static void main(String ... args) {
        String text = U.fetch("https://stackoverflow.com/questions"
        + "/921262/how-to-download-and-save-a-file-from-internet-using-java").text();
    }
}

Fatal error: Maximum execution time of 30 seconds exceeded

Follow the path /etc/php5(your php version)/apache2/php.ini.

Open it and set the value of max_execution_time to a desired one.

Clearing Magento Log Data

you can disable or set date and time for log setting.

System > Configuration > Advanced > System > Log Cleaning

JSON Structure for List of Objects

The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.

This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

Solution for me (Android Studio) :

1) Use shortcut Ctrl+Shift+Alt+S or File -> Project Structure

2) and increase the level of SDK "Compile SDK Version".

Angular 2: How to write a for loop, not a foreach loop

   queNumMin = 23;
   queNumMax= 26;
   result = 0;
for (let index = this.queNumMin; index <= this.queNumMax; index++) {
         this.result = index
         console.log( this.result);
     }

Range min and max number

Importing CSV with line breaks in Excel 2007

What just worked for me, importing into Excel directly provided that the import is done as a text format instead as csv format. M/

Jetty: HTTP ERROR: 503/ Service Unavailable

I had the same problem. I solved it by removing the line break from the xml file. I did

<operationBindings>
    <OperationBinding>
        <operationType>update</operationType>
        <operationId>makePdf</operationId>
        <serverObject>
            <className>com.myclass</className>
            <lookupStyle>new</lookupStyle>
        </serverObject>
        <serverMethod>makePdf</serverMethod>
    </OperationBinding>
</operationBindings>

instead of ...

<serverObject>
            <className>com.myclass
</className>
            <lookupStyle>new</lookupStyle>
</serverObject>

What is the height of Navigation Bar in iOS 7?

There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.

Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

Focusable EditText inside ListView

this post was matching exactly my keywords. I have a ListView header with a search EditText and a search Button.

In order to give focus to the EditText after loosing the initial focus the only HACK that i found is:

    searchText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // LOTS OF HACKS TO MAKE THIS WORK.. UFF...
            searchButton.requestFocusFromTouch();
            searchText.requestFocus();
        }
    });

Lost lots of hours and it's not a real fix. Hope it helps someone tough.

DataGridView.Clear()

If you want clear a dataGridView not binded to DataSource but manually loaded you can use this simple code:

datagridview.Rows.Clear();
datagridview.Columns.Clear();

How do I modify the URL without reloading the page?

As pointed out by Thomas Stjernegaard Jeppesen, you could use History.js to modify URL parameters whilst the user navigates through your Ajax links and apps.

Almost an year has passed since that answer, and History.js grew and became more stable and cross-browser. Now it can be used to manage history states in HTML5-compliant as well as in many HTML4-only browsers. In this demo You can see an example of how it works (as well as being able to try its functionalities and limits.

Should you need any help in how to use and implement this library, i suggest you to take a look at the source code of the demo page: you will see it's very easy to do.

Finally, for a comprehensive explanation of what can be the issues about using hashes (and hashbangs), check out this link by Benjamin Lupton.

Select row and element in awk

Since awk and perl are closely related...


Perl equivalents of @Dennis's awk solutions:

To print the second line:
perl -ne 'print if $. == 2' file

To print the second field:
perl -lane 'print $F[1]' file

To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file


Perl equivalent of @Glenn's solution:

Print the j'th field of the i'th line

perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file


Perl equivalents of @Hai's solutions:

if you are looking for second columns that contains abc:

perl -lane 'print if $F[1] =~ /abc/' foo

... and if you want to print only a particular column:

perl -lane 'print $F[2] if $F[1] =~ /abc/' foo

... and for a particular line number:

perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo


-l removes newlines, and adds them back in when printing
-a autosplits the input line into array @F, using whitespace as the delimiter
-n loop over each line of the input file
-e execute the code within quotes
$F[1] is the second element of the array, since Perl starts at 0
$. is the line number

How do you specify the Java compiler version in a pom.xml file?

Generally you don't want to value only the source version (javac -source 1.8 for example) but you want to value both the source and the target version (javac -source 1.8 -target 1.8 for example).
Note that from Java 9, you have a way to convey both information and in a more robust way for cross-compilation compatibility (javac -release 9).
Maven that wraps the javac command provides multiple ways to convey all these JVM standard options.

How to specify the JDK version?

Using maven-compiler-plugin or maven.compiler.source/maven.compiler.target properties to specify the source and the target are equivalent.

<plugins>
    <plugin>    
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>

and

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

are equivalent according to the Maven documentation of the compiler plugin since the <source> and the <target> elements in the compiler configuration use the properties maven.compiler.source and maven.compiler.target if they are defined.

source

The -source argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.source.

target

The -target argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.target.

About the default values for source and target, note that since the 3.8.0 of the maven compiler, the default values have changed from 1.5 to 1.6.

<release> tag — new way to specify Java version in maven-compiler-plugin 3.6

You can use the release argument :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>9</release>
    </configuration>
</plugin>

You could also declare just the user property maven.compiler.release:

<properties>
    <maven.compiler.release>9</maven.compiler.release>
</properties>

But at this time the last one will not be enough as the maven-compiler-plugin default version you use doesn't rely on a recent enough version.

The Maven release argument conveys release to the Java compiler to access the JVM standard option newly added to Java 9, JEP 247: Compile for Older Platform Versions.

Compiles against the public, supported and documented API for a specific VM version.

This way provides a standard way to specify the same version for the source, the target and the bootstrap JVM options.
Note that specifying the bootstrap is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.

Which is the best way to specify the JDK version?

Java 8 and below

Neither maven.compiler.source/maven.compiler.target properties or using the maven-compiler-plugin is better. It changes nothing in the facts since finally the two ways rely on the same properties and the same mechanism : the maven core compiler plugin.

Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:

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

Java 9 and later

The release argument (third point) is a way to strongly consider if you want to use the same version for the source and the target.

Interface/enum listing standard mime-type constants

If you're on android you have multiple choices, where only the first is a kind of "enum":

For example

@Override
public String getType(Uri uri) {
    return URLConnection.getFileNameMap().getContentTypeFor(
            uri.getLastPathSegment());
}

How can I delete all cookies with JavaScript?

On the face of it, it looks okay - if you call eraseCookie() on each cookie that is read from document.cookie, then all of your cookies will be gone.

Try this:

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
  eraseCookie(cookies[i].split("=")[0]);

All of this with the following caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

How to return a list of keys from a Hash Map?

 for(int i=0;i<ytFiles.size();i++){

                    int key = ytFiles.keyAt(i);
                    Log.e("key", String.valueOf(key));
                    String format = ytFiles.get(key).getFormat().toString();
                    String url = ytFiles.get(key).getUrl();
                    Log.e("url",url);
                }

you can get key by method keyat and you have to pass the index then it will return key at that particular index. this loop will get all the key

How to parse JSON in Kotlin?

Without external library (on Android)

To parse this:

val jsonString = """
    {
       "type":"Foo",
       "data":[
          {
             "id":1,
             "title":"Hello"
          },
          {
             "id":2,
             "title":"World"
          }
       ]
    }        
"""

Use these classes:

import org.json.JSONObject

class Response(json: String) : JSONObject(json) {
    val type: String? = this.optString("type")
    val data = this.optJSONArray("data")
            ?.let { 0.until(it.length()).map { i -> it.optJSONObject(i) } } // returns an array of JSONObject
            ?.map { Foo(it.toString()) } // transforms each JSONObject of the array into Foo
}

class Foo(json: String) : JSONObject(json) {
    val id = this.optInt("id")
    val title: String? = this.optString("title")
}

Usage:

val foos = Response(jsonString)

AppFabric installation failed because installer MSI returned with error code : 1603

So, I was having the same issue. The main reason I am installing Appfabric is to create a SharePoint 2013 development server.
What did not work:

  • Updating the Environmental Variable PSModulePath - did not work. Still recieved the 1603 error after running the setup agian.
  • tried to find the registry entries. Could not find them.

What worked for me to get Appfrabic installed was installing from the setup file via powershell. Woo hoo! It worked for me! This is the link I retrieved the commands from: Installing AppFabric 1.1 with PowerShell DSC results in modal dialog error

        Start-Process -FilePath 'c:\temp\SharePoint\pre\appfabric\setup.exe' -ArgumentList '/i cacheclient","cachingService","CacheAdmin /gac /l c:\temp\appfabric.log' -Wait | Write-verbose
        Start-Process -FilePath 'c:\temp\SharePoint\pre\AppFabric1.1-RTM-KB2671763-x64-ENU.exe' -ArgumentList '/quiet' -Wait | Write-verbose

I hope this helps others with the same issue.

pandas: find percentile stats of a given column

You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)

my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])

Tri-state Check box in HTML?

Here other Example with simple jQuery and property data-checked:

_x000D_
_x000D_
 $("#checkbox")_x000D_
  .click(function(e) {_x000D_
    var el = $(this);_x000D_
_x000D_
    switch (el.data('checked')) {_x000D_
_x000D_
      // unchecked, going indeterminate_x000D_
      case 0:_x000D_
        el.data('checked', 1);_x000D_
        el.prop('indeterminate', true);_x000D_
        break;_x000D_
_x000D_
        // indeterminate, going checked_x000D_
      case 1:_x000D_
        el.data('checked', 2);_x000D_
        el.prop('indeterminate', false);_x000D_
        el.prop('checked', true);_x000D_
        break;_x000D_
_x000D_
        // checked, going unchecked_x000D_
      default:_x000D_
        el.data('checked', 0);_x000D_
        el.prop('indeterminate', false);_x000D_
        el.prop('checked', false);_x000D_
_x000D_
    }_x000D_
  });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<label><input type="checkbox" name="checkbox" value="" checked id="checkbox"> Tri-State Checkbox </label>
_x000D_
_x000D_
_x000D_

How to fire an event on class change using jQuery?

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});

UPDATE

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

_x000D_
_x000D_
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  mutations.forEach(function(mutation) {_x000D_
    if (mutation.attributeName === "class") {_x000D_
      var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
      console.log("Class attribute changed to:", attributeValue);_x000D_
    }_x000D_
  });_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
  attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
_x000D_
_x000D_

Be aware that the MutationObserver is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.

How to restore default perspective settings in Eclipse IDE

One way is just to revert your settings: If you delete the Metadata folder in your workspace eclipse will revert to its factory state for all settings (both perspective and general).

Source: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka11640.html

jQuery: selecting each td in a tr

$('#tblNewAttendees tbody tr).each((index, tr)=> {
        //console.log(tr);
        $(tr).children('td').each ((index, td) => {
            console.log(td);

        }); 

    });

You can use this tr and td parameter also.

How to convert date format to DD-MM-YYYY in C#

string formatted = date.ToString("dd-MM-yyyy");

will do it.

Here is a good reference for different formats.

Markdown open a new window link

You can edit the generated markup and add

target = "_blank"

The type WebMvcConfigurerAdapter is deprecated

Use org.springframework.web.servlet.config.annotation.WebMvcConfigurer

With Spring Boot 2.1.4.RELEASE (Spring Framework 5.1.6.RELEASE), do like this

package vn.bkit;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // Deprecated.
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

Google reCAPTCHA: How to get user response and validate in the server side?

The cool thing about the new Google Recaptcha is that the validation is now completely encapsulated in the widget. That means, that the widget will take care of asking questions, validating responses all the way till it determines that a user is actually a human, only then you get a g-recaptcha-response value.

But that does not keep your site safe from HTTP client request forgery.

Anyone with HTTP POST knowledge could put random data inside of the g-recaptcha-response form field, and foll your site to make it think that this field was provided by the google widget. So you have to validate this token.

In human speech it would be like,

  • Your Server: Hey Google, there's a dude that tells me that he's not a robot. He says that you already verified that he's a human, and he told me to give you this token as a proof of that.
  • Google: Hmm... let me check this token... yes I remember this dude I gave him this token... yeah he's made of flesh and bone let him through.
  • Your Server: Hey Google, there's another dude that tells me that he's a human. He also gave me a token.
  • Google: Hmm... it's the same token you gave me last time... I'm pretty sure this guy is trying to fool you. Tell him to get off your site.

Validating the response is really easy. Just make a GET Request to

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

And replace the response_string with the value that you earlier got by the g-recaptcha-response field.

You will get a JSON Response with a success field.

More information here: https://developers.google.com/recaptcha/docs/verify

Edit: It's actually a POST, as per documentation here.

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

Extract the last substring from a cell

Try this function in Excel:

Public Shared Function SPLITTEXT(Text As String, SplitAt As String, ReturnZeroBasedIndex As Integer) As String
        Dim s() As String = Split(Text, SplitAt)
        If ReturnZeroBasedIndex <= s.Count - 1 Then
            Return s(ReturnZeroBasedIndex)
        Else
            Return ""
        End If
    End Function

You use it like this:

First Name (A1) | Last Name (A2)

Value in cell A1 = Michael Zomparelli

I want the last name in column A2.

=SPLITTEXT(A1, " ", 1)

The last param is the zero-based index you want to return. So if you split on the space char then index 0 = Michael and index 1 = Zomparelli

The above function is a .Net function, but can easily be converted to VBA.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

I work for a large corporation and encountered this same error, but needed a different work around. My issue was related to proxy settings. I had my proxy set up so I needed to set my no_proxy to whitelist AWS before I was able to get everything to work. You can set it in your bash script as well if you don't want to muddy up your Python code with os settings.

Python:

import os
os.environ["NO_PROXY"] = "s3.amazonaws.com"

Bash:

export no_proxy = "s3.amazonaws.com"

Edit: The above assume a US East S3 region. For other regions: use s3.[region].amazonaws.com where region is something like us-east-1 or us-west-2

How are parameters sent in an HTTP POST request?

Some of the webservices require you to place request data and metadata separately. For example a remote function may expect that the signed metadata string is included in a URI, while the data is posted in a HTTP-body.

The POST request may semantically look like this:

POST /?AuthId=YOURKEY&Action=WebServiceAction&Signature=rcLXfkPldrYm04 HTTP/1.1
Content-Type: text/tab-separated-values; charset=iso-8859-1
Content-Length: []
Host: webservices.domain.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)

name    id
John    G12N
Sarah   J87M
Bob     N33Y

This approach logically combines QueryString and Body-Post using a single Content-Type which is a "parsing-instruction" for a web-server.

Please note: HTTP/1.1 is wrapped with the #32 (space) on the left and with #10 (Line feed) on the right.

Variables declared outside function

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5
>>> def fn():
...     print(global_var)
... 
>>> fn()
5
>>> def fn_2():
...     global_var += 2
...     print(global_var)
... 
>>> fn_2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
...     global global_var
...     global_var += 2
...     print(global_var)
... 
>>> fn_3()
7

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

How to get the selected index of a RadioGroup in Android

try this

        RadioGroup  group= (RadioGroup) getView().findViewById(R.id.radioGroup);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                View radioButton = radioGroup.findViewById(i);
                int index = radioGroup.indexOfChild(radioButton);
            }
        });

Executable directory where application is running from?

This is the first post on google so I thought I'd post different ways that are available and how they compare. Unfortunately I can't figure out how to create a table here, so it's an image. The code for each is below the image using fully qualified names.

enter image description here

My.Application.Info.DirectoryPath

Environment.CurrentDirectory

System.Windows.Forms.Application.StartupPath

AppDomain.CurrentDomain.BaseDirectory

System.Reflection.Assembly.GetExecutingAssembly.Location

System.Reflection.Assembly.GetExecutingAssembly.CodeBase

New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase)

Path.GetDirectoryName(Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path)))

Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path))

Turning off hibernate logging console output

You can disabled the many of the outputs of hibernate setting this props of hibernate (hb configuration) a false:

hibernate.show_sql
hibernate.generate_statistics
hibernate.use_sql_comments

But if you want to disable all console info you must to set the logger level a NONE of FATAL of class org.hibernate like Juha say.

How do I print the key-value pairs of a dictionary in python

>>> d={'a':1,'b':2,'c':3}
>>> for kv in d.items():
...     print kv[0],'\t',kv[1]
... 
a   1
c   3
b   2

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

How can I get the current stack trace in Java?

To get the stack trace of all threads you can either use the jstack utility, JConsole or send a kill -quit signal (on a Posix operating system).

However, if you want to do this programmatically you could try using ThreadMXBean:

ThreadMXBean bean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos = bean.dumpAllThreads(true, true);

for (ThreadInfo info : infos) {
  StackTraceElement[] elems = info.getStackTrace();
  // Print out elements, etc.
}

As mentioned, if you only want the stack trace of the current thread it's a lot easier - Just use Thread.currentThread().getStackTrace();

Match line break with regular expression

You could search for:

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

And replace with:

$0</a>

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


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

AngularJS ng-class if-else expression

Use it this way:

    <div [ngClass]="{cssClass A: condition 1, cssClass B: condition 2, cssClass C: condition 3}">...</div>

Java: how to add image to Jlabel?

(If you are using NetBeans IDE) Just create a folder in your project but out side of src folder. Named the folder Images. And then put the image into the Images folder and write code below.

// Import ImageIcon     
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);

Now run your program.

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

ObjectId is composed of following things.

  1. a 4-byte value representing the seconds since the Unix epoch
  2. a 5-byte random value (Machine ID 3 bytes and Processor id 2 bytes)
  3. a 3-byte counter, starting with a random value.

Correct way to validate if the objectId is valid is by using static method from ObjectId class itself.

mongoose.Types.ObjectId.isValid(sample_object_id)

How to recompile with -fPIC

In addirion to the good answers here, specifically Robert Lujo's.

I want to say in my case I've been deliberately trying to statically compile a version of ffmpeg. All the required dependencies and what else heretofore required, I've done static compilation.

When I ran ./configure for the ffmpeg process I didnt notice --enable-shared was on the commandline. Removing it and running ./configure is only then I was able to compile correctly (All 56 mbs of an ffmpeg binary). Check that out as well if your intention is static compilation

fs.writeFile in a promise, asynchronous-synchronous stuff

For easy to use asynchronous convert all callback to promise use some library like "bluebird" .

      .then(function(results) {
                fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("JSON saved");
                        return results;
                    }
                })


            }).catch(function(err) {
                console.log(err);
            });

Try solution with promise (bluebird)

var amazon = require('amazon-product-api');
var fs = require('fs');
var Promise = require('bluebird');

var client = amazon.createClient({
    awsId: "XXX",
    awsSecret: "XXX",
    awsTag: "888"
});


var array = fs.readFileSync('./test.txt').toString().split('\n');
Promise.map(array, function (ASIN) {
    client.itemLookup({
        domain: 'webservices.amazon.de',
        responseGroup: 'Large',
        idType: 'ASIN',
        itemId: ASIN
    }).then(function(results) {
        fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
            if (err) {
                console.log(err);
            } else {
                console.log("JSON saved");
                return results;
            }
        })
    }).catch(function(err) {
        console.log(err);
    });
});

How to really read text file from classpath in Java

This is how I read all lines of a text file on my classpath, using Java 7 NIO:

...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

...

Files.readAllLines(
    Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());

NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.

Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets (these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").

Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8

Mongodb: failed to connect to server on first connect

While connected to a wifi network, mongodb://localhost/db_name worked as expected.

When I wasn't connected to any wifi network, this couldn't work. Instead I used, mongodb://127.0.0.1/db_name and it worked.

Probably a problem to do with ip configurations.

"’" showing on page instead of " ' "

The same thing happened to me with the '–' character (long minus sign).
I used this simple replace so resolve it:

htmlText = htmlText.Replace('–', '-');

No Activity found to handle Intent : android.intent.action.VIEW

I have two ideas:

First: if you want to play 3gp file you should use mime types "audio/3gpp" or "audio/mpeg"

And second: you can try use method setData(data) for intent without any mime type.

Generating statistics from Git repository

If your project is on GitHub, you now (April 2013) have Pulse (see "Get up to speed with Pulse"):

It is more limited, and won't display all the stats you might need, but is readily available for any GitHub project.

Pulse is a great way to discover recent activity on projects.
Pulse will show you who has been actively committing and what has changed in a project's default branch:

Pulse

You can find the link to the left of the nav bar.

Link

Note that there isn't (yet) an API to extract that information.

What's the best way to check if a String represents an integer in Java?

Find this may helpful:

public static boolean isInteger(String self) {
    try {
        Integer.valueOf(self.trim());
        return true;
    } catch (NumberFormatException nfe) {
        return false;
    }
}

Connection timeout for SQL server

Yes, you could append ;Connection Timeout=30 to your connection string and specify the value you wish.

The timeout value set in the Connection Timeout property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).

Moreover, setting the timeout value to 0, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:

A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.

How to set image on QPushButton?

I don't think you can set arbitrarily sized images on any of the existing button classes. If you want a simple image behaving like a button, you can write your own QAbstractButton-subclass, something like:

class ImageButton : public QAbstractButton {
Q_OBJECT
public:
...
    void setPixmap( const QPixmap& pm ) { m_pixmap = pm; update(); }
    QSize sizeHint() const { return m_pixmap.size(); }
protected:
    void paintEvent( QPaintEvent* e ) {
        QPainter p( this );
        p.drawPixmap( 0, 0, m_pixmap );
    }
};

What is the purpose of nameof?

The purpose of the nameof operator is to provide the source name of the artifacts.

Usually the source name is the same name as the metadata name:

public void M(string p)
{
    if (p == null)
    {
        throw new ArgumentNullException(nameof(p));
    }
    ...
}

public int P
{
    get
    {
        return p;
    }
    set
    {
        p = value;
        NotifyPropertyChanged(nameof(P));
    }
}

But this may not always be the case:

using i = System.Int32;
...
Console.WriteLine(nameof(i)); // prints "i"

Or:

public static string Extension<T>(this T t)
{
    return nameof(T); returns "T"
}

One use I've been giving to it is for naming resources:

[Display(
    ResourceType = typeof(Resources),
    Name = nameof(Resources.Title_Name),
    ShortName = nameof(Resources.Title_ShortName),
    Description = nameof(Resources.Title_Description),
    Prompt = nameof(Resources.Title_Prompt))]

The fact is that, in this case, I didn't even need the generated properties to access the resources, but now I have a compile time check that the resources exist.

Converting PHP result array to JSON

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Probably the jstl libraries are missing from your classpath/not accessible by tomcat.

You need to add at least the following jar files in your WEB-INF/lib directory:

  • jsf-impl.jar
  • jsf-api.jar
  • jstl.jar

Simple way to unzip a .zip file using zlib

Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.

Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.

// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>

#include "unzip.h"

#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192

int main( int argc, char **argv )
{
    if ( argc < 2 )
    {
        printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
        return -1;
    }

    // Open the zip file
    unzFile *zipfile = unzOpen( argv[ 1 ] );
    if ( zipfile == NULL )
    {
        printf( "%s: not found\n" );
        return -1;
    }

    // Get info about the zip file
    unz_global_info global_info;
    if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
    {
        printf( "could not read file global info\n" );
        unzClose( zipfile );
        return -1;
    }

    // Buffer to hold data read from the zip file.
    char read_buffer[ READ_SIZE ];

    // Loop to extract all files
    uLong i;
    for ( i = 0; i < global_info.number_entry; ++i )
    {
        // Get info about current file.
        unz_file_info file_info;
        char filename[ MAX_FILENAME ];
        if ( unzGetCurrentFileInfo(
            zipfile,
            &file_info,
            filename,
            MAX_FILENAME,
            NULL, 0, NULL, 0 ) != UNZ_OK )
        {
            printf( "could not read file info\n" );
            unzClose( zipfile );
            return -1;
        }

        // Check if this entry is a directory or file.
        const size_t filename_length = strlen( filename );
        if ( filename[ filename_length-1 ] == dir_delimter )
        {
            // Entry is a directory, so create it.
            printf( "dir:%s\n", filename );
            mkdir( filename );
        }
        else
        {
            // Entry is a file, so extract it.
            printf( "file:%s\n", filename );
            if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
            {
                printf( "could not open file\n" );
                unzClose( zipfile );
                return -1;
            }

            // Open a file to write out the data.
            FILE *out = fopen( filename, "wb" );
            if ( out == NULL )
            {
                printf( "could not open destination file\n" );
                unzCloseCurrentFile( zipfile );
                unzClose( zipfile );
                return -1;
            }

            int error = UNZ_OK;
            do    
            {
                error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
                if ( error < 0 )
                {
                    printf( "error %d\n", error );
                    unzCloseCurrentFile( zipfile );
                    unzClose( zipfile );
                    return -1;
                }

                // Write data to file.
                if ( error > 0 )
                {
                    fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
                }
            } while ( error > 0 );

            fclose( out );
        }

        unzCloseCurrentFile( zipfile );

        // Go the the next entry listed in the zip file.
        if ( ( i+1 ) < global_info.number_entry )
        {
            if ( unzGoToNextFile( zipfile ) != UNZ_OK )
            {
                printf( "cound not read next file\n" );
                unzClose( zipfile );
                return -1;
            }
        }
    }

    unzClose( zipfile );

    return 0;
}

I built and tested it with MinGW/MSYS on Windows like this:

contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

I had the same problem, to solve it set specific user from domain in iis -> action sidebar->Basic Settings -> Connect as... -> specific user

enter image description here

You are trying to add a non-nullable field 'new_field' to userprofile without a default

In new_file add the boolean property null.

new_field = models.CharField(max_length=140, null=True)

after you run a ./manage.py syncdb for refresh the DB. and finally you run ./manage.py makemigrations and ./manage.py migrate

How to ssh connect through python Paramiko with ppk public key

For me I doing this:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

works for me pretty ok

What is the difference between function and procedure in PL/SQL?

  1. we can call a stored procedure inside stored Procedure,Function within function ,StoredProcedure within function but we can not call function within stored procedure.
  2. we can call function inside select statement.
  3. We can return value from function without passing output parameter as a parameter to the stored procedure.

This is what the difference i found. Please let me know if any .

Get class labels from Keras functional model

It is possible to save a "list" of labels in keras model directly. This way the user who uses the model for predictions and does not have any other sources of information can perform the lookup himself. Here is a dummy example of how one can perform an "injection" of labels

# assume we get labels as list
labels = ["cat","dog","horse","tomato"]
# here we start building our model with input image 299x299 and one output layer
xx = Input(shape=(299,299,3))
flat = Flatten()(xx)
output = Dense(shape=(4))(flat)
# here we perform injection of labels
tf_labels = tf.constant([labels],dtype="string")
tf_labels = tf.tile(labels,[tf.shape(xx)[0],1])
output_labels = Lambda(lambda x: tf_labels,name="label_injection")(xx)
#and finaly creating a model
model=tf.keras.Model(xx,[output,output_labels])

When used for prediction, this model returns tensor of scores and tensot of string labels. Model like this can be saved to h5. In this case the file contains the labels. This model can also be exported to saved_model and used for serving in the cloud.

What .NET collection provides the fastest search

If you're using .Net 3.5, you can make cleaner code using:

foreach (Record item in LookupCollection.Intersect(LargeCollection))
{
  //dostuff
}

I don't have .Net 3.5 here and so this is untested. It relies on an extension method. Not that LookupCollection.Intersect(LargeCollection) is probably not the same as LargeCollection.Intersect(LookupCollection) ... the latter is probably much slower.

This assumes LookupCollection is a HashSet

How to use Python to login to a webpage and retrieve cookies for later usage?

Here's a version using the excellent requests library:

from requests import session

payload = {
    'action': 'login',
    'username': USERNAME,
    'password': PASSWORD
}

with session() as c:
    c.post('http://example.com/login.php', data=payload)
    response = c.get('http://example.com/protected_page.php')
    print(response.headers)
    print(response.text)

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

this worked for me

// using Microsoft.AspNetCore.Authentication.Cookies;
// using Microsoft.AspNetCore.Http;

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
        options =>
        {
            options.LoginPath = new PathString("/auth/login");
            options.AccessDeniedPath = new PathString("/auth/denied");
        });

How do I fix twitter-bootstrap on IE?

If you are using responsive layout, try including this js on your code: https://github.com/scottjehl/Respond

How to subtract/add days from/to a date?

Just subtract a number:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

Since the Date class only has days, you can just do basic arithmetic on it.

If you want to use POSIXlt for some reason, then you can use it's slots:

> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"

Change Active Menu Item on Page Scroll?

It's done by binding to the scroll event of the container (usually window).

Quick example:

// Cache selectors
var topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   // Set/remove active class
   menuItems
     .parent().removeClass("active")
     .end().filter("[href='#"+id+"']").parent().addClass("active");
});?

See the above in action at jsFiddle including scroll animation.

python setup.py uninstall

First record the files you have installed. You can repeat this command, even if you have previously run setup.py install:

python setup.py install --record files.txt

When you want to uninstall you can just:

sudo rm $(cat files.txt)

This works because the rm command takes a whitespace-seperated list of files to delete and your installation record is just such a list.

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

First, you need to change the "project bytecode version" under File > Settings, Compiler > Java Compiler

Second, do a full rebuild.

“Unable to find manifest signing certificate in the certificate store” - even when add new key

To sign an assembly with a strong name using attributes

Open AssemblyInfo.cs (in $(SolutionDir)\Properties)

the AssemblyKeyFileAttribute or the AssemblyKeyNameAttribute, specifying the name of the file or container that contains the key pair to use when signing the assembly with a strong name.

add the following code:

[assembly:AssemblyKeyFileAttribute("keyfile.snk")]

MySQL remove all whitespaces from the entire column

Since the question is how to replace ALL whitespaces

UPDATE `table` 
SET `col_name` = REPLACE
(REPLACE(REPLACE(`col_name`, ' ', ''), '\t', ''), '\n', '');

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Setting environment variables for accessing in PHP when using Apache

You can also do this in a .htaccess file assuming they are enabled on the website.

SetEnv KOHANA_ENV production

Would be all you need to add to a .htaccess to add the environment variable

What is `git push origin master`? Help with git's refs, heads and remotes

Or as a single command:

git push -u origin master:my_test

Pushes the commits from your local master branch to a (possibly new) remote branch my_test and sets up master to track origin/my_test.

Converting SVG to PNG using C#

When I had to rasterize svgs on the server, I ended up using P/Invoke to call librsvg functions (you can get the dlls from a windows version of the GIMP image editing program).

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetDllDirectory(string pathname);

[DllImport("libgobject-2.0-0.dll", SetLastError = true)]
static extern void g_type_init(); 

[DllImport("librsvg-2-2.dll", SetLastError = true)]
static extern IntPtr rsvg_pixbuf_from_file_at_size(string file_name, int width, int height, out IntPtr error);

[DllImport("libgdk_pixbuf-2.0-0.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
static extern bool gdk_pixbuf_save(IntPtr pixbuf, string filename, string type, out IntPtr error, __arglist);

public static void RasterizeSvg(string inputFileName, string outputFileName)
{
    bool callSuccessful = SetDllDirectory("C:\\Program Files\\GIMP-2.0\\bin");
    if (!callSuccessful)
    {
        throw new Exception("Could not set DLL directory");
    }
    g_type_init();
    IntPtr error;
    IntPtr result = rsvg_pixbuf_from_file_at_size(inputFileName, -1, -1, out error);
    if (error != IntPtr.Zero)
    {
        throw new Exception(Marshal.ReadInt32(error).ToString());
    }
    callSuccessful = gdk_pixbuf_save(result, outputFileName, "png", out error, __arglist(null));
    if (!callSuccessful)
    {
        throw new Exception(error.ToInt32().ToString());
    }
}

How do I restart a service on a remote machine in Windows?

You can use System Internals PSEXEC command to remotely execute a net stop yourservice, then net start yourservice

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

When you're working with strings in PHP you'll need to pay special attention to the formation, using " or '

$string = 'Hello, world!';
$string = "Hello, world!";

Both of these are valid, the following is not:

$string = "Hello, world';

You must also note that ' inside of a literal started with " will not end the string, and vice versa. So when you have a string which contains ', it is generally best practice to use double quotation marks.

$string = "It's ok here";

Escaping the string is also an option

$string = 'It\'s ok here too';

More information on this can be found within the documentation

How to upload a file in Django?

Here it may helps you: create a file field in your models.py

For uploading the file(in your admin.py):

def save_model(self, request, obj, form, change):
    url = "http://img.youtube.com/vi/%s/hqdefault.jpg" %(obj.video)
    url = str(url)

    if url:
        temp_img = NamedTemporaryFile(delete=True)
        temp_img.write(urllib2.urlopen(url).read())
        temp_img.flush()
        filename_img = urlparse(url).path.split('/')[-1]
        obj.image.save(filename_img,File(temp_img)

and use that field in your template also.

Head and tail in one line

Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.

t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]

If you need it to be exception-proof (i.e. supporting empty list), then add:

t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]

If you want to do it without the semicolon, use:

h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

Spring Boot - Cannot determine embedded database driver class for database type NONE

I tried all the mentioned things above but could not resolve the issue. I am using SQLite and my SQLite file was in the resources directory.

a) Set Up done for IDE

I need to manually add below lines in the .classpath file of my project.

<classpathentry kind="src" path="resources"/>
<classpathentry kind="output" path="target/classes"/>

After that, I refreshed and Cleaned the project from MenuBar at the top. like Project->Clean->My Project Name.

After that, I run the project and problem resolved.

application.properties for my project is

spring.datasource.url=jdbc:sqlite:resources/apiusers.sqlite
spring.datasource.driver-class-name=org.sqlite.JDBC
spring.jpa.properties.hibernate.dialect=com.enigmabridge.hibernate.dialect.SQLiteDialect
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update

b) Set Up done if Jar deployment throw same error

You need to add following lines to your pom.xml

  <build>
        <resources>
        <resource>
            <directory>resources</directory>
            <targetPath>${project.build.outputDirectory}</targetPath>
            <includes>
                <include>application.properties</include>
            </includes>
        </resource>
    </resources>
</build>

May be it may help someone.

Take multiple lists into dataframe

you can simple use this following code

train_data['labels']= train_data[["LABEL1","LABEL1","LABEL2","LABEL3","LABEL4","LABEL5","LABEL6","LABEL7"]].values.tolist()
train_df = pd.DataFrame(train_data, columns=['text','labels'])

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

int value under 10 convert to string two digit number

This blog post is a great little cheat-sheet to keep handy when trying to format strings to a variety of formats.

link to trojan removed

Edit

The link was removed because Google temporarily warned that the site (or related site) may have been spreading malicious software. It is now off the list an no longer reported as problematic. Google "SteveX String Formatting" you'll find the search result and you can visit it at your discretion.

Why is it common to put CSRF prevention tokens in cookies?

Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.

The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.

The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.

How to do multiline shell script in Ansible

Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:

  • The > is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:

    key: >
      This text
      has multiple
      lines
    

    Would assign the value This text has multiple lines\n to key.

  • The | character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:

    key: |
      This text
      has multiple
      lines
    

    Would assign the value This text\nhas multiple\nlines\n to key.

You can use this for multiline shell scripts like this:

- name: iterate user groups
  shell: |
    groupmod -o -g {{ item['guid'] }} {{ item['username'] }} 
    do_some_stuff_here
    and_some_other_stuff
  with_items: "{{ users }}"

There is one caveat: Ansible does some janky manipulation of arguments to the shell command, so while the above will generally work as expected, the following won't:

- shell: |
    cat <<EOF
    This is a test.
    EOF

Ansible will actually render that text with leading spaces, which means the shell will never find the string EOF at the beginning of a line. You can avoid Ansible's unhelpful heuristics by using the cmd parameter like this:

- shell:
    cmd: |
      cat <<EOF
      This is a test.
      EOF

How to show imageView full screen on imageView click?

It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)

    public class UIutils {

private Activity mActivity;

    public UIutils(Activity activity){
        mActivity = activity;
    }

public void showPhoto(Uri photoUri){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(photoUri, "image/*");
        mActivity.startActivity(intent);
    }
}

Then to use it just do this:

imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));

I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.