Programs & Examples On #Code statistics

How does String substring work in Swift

Swift 5 Extension:

extension String {
    subscript(_ range: CountableRange<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
        let end = index(start, offsetBy: min(self.count - range.lowerBound, 
                                             range.upperBound - range.lowerBound))
        return String(self[start..<end])
    }

    subscript(_ range: CountablePartialRangeFrom<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
         return String(self[start...])
    }
}

Usage:

let s = "hello"
s[0..<3] // "hel"
s[3...]  // "lo"

Or unicode:

let s = ""
s[0..<1] // ""

Socket accept - "Too many open files"

Use lsof -u `whoami` | wc -l to find how many open files the user has

Escape invalid XML characters in C#

// Replace invalid characters with empty strings.
   Regex.Replace(inputString, @"[^\w\.@-]", ""); 

The regular expression pattern [^\w.@-] matches any character that is not a word character, a period, an @ symbol, or a hyphen. A word character is any letter, decimal digit, or punctuation connector such as an underscore. Any character that matches this pattern is replaced by String.Empty, which is the string defined by the replacement pattern. To allow additional characters in user input, add those characters to the character class in the regular expression pattern. For example, the regular expression pattern [^\w.@-\%] also allows a percentage symbol and a backslash in an input string.

Regex.Replace(inputString, @"[!@#$%_]", "");

Refer this too :

Removing Invalid Characters from XML Name Tag - RegEx C#

Here is a function to remove the characters from a specified XML string:

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace XMLUtils
{
    class Standards
    {
        /// <summary>
        /// Strips non-printable ascii characters 
        /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
        /// Refer to http://www.w3.org/TR/2006/REC-xml-20060816/#charsets for XML 1.0
        /// </summary>
        /// <param name="content">contents</param>
        /// <param name="XMLVersion">XML Specification to use. Can be 1.0 or 1.1</param>
        private void StripIllegalXMLChars(string tmpContents, string XMLVersion)
        {    
            string pattern = String.Empty;
            switch (XMLVersion)
            {
                case "1.0":
                    pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])";
                    break;
                case "1.1":
                    pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])";
                    break;
                default:
                    throw new Exception("Error: Invalid XML Version!");
            }

            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
            if (regex.IsMatch(tmpContents))
            {
                tmpContents = regex.Replace(tmpContents, String.Empty);
            }
            tmpContents = string.Empty;
        }
    }
}

Gradle finds wrong JAVA_HOME even though it's correctly set

In my Ubuntu, I have a headache for 2 days on this issue.

Step 1. Type on the terminal whereis java then it will display something like this

java: /usr/bin/java /etc/java /usr/share/java /usr/lib/jvm/java-8-openjdk-amd64/bin/java /usr/share/man/man1/java.1.gz

Step 2. Take note of the path: /usr/lib/jvm/java-8-openjdk-amd64/bin/java

exclude the bin/java

your JAVA_HOME = /usr/lib/jvm/java-8-openjdk-amd64

Android RecyclerView addition & removal of items

In the activity:

mAdapter.updateAt(pos, text, completed);
mAdapter.removeAt(pos);

In the your adapter:

void removeAt(int position) {
    list.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, list.size());
}

void updateAt(int position, String text, Boolean completed) {
    TodoEntity todoEntity = list.get(position);
    todoEntity.setText(text);
    todoEntity.setCompleted(completed);
    notifyItemChanged(position);
}

Finding median of list in Python

Just two lines are enough.

def get_median(arr):
    '''
    Calculate the median of a sequence.
    :param arr: list
    :return: int or float
    '''
    arr.sort()
    return arr[len(arr)//2] if len(arr) % 2 else (arr[len(arr)//2] + arr[len(arr)//2-1])/2

How to convert text to binary code in JavaScript?

var PADDING = "00000000"

var string = "TEST"
var resultArray = []

for (var i = 0; i < string.length; i++) {
  var compact = string.charCodeAt(i).toString(2)
  var padded  = compact.substring(0, PADDING.length - compact.length) + compact

  resultArray.push(padded)
}

console.log(resultArray.join(" "))

Can an html element have multiple ids?

No. Every DOM element, if it has an id, has a single, unique id. You could approximate it using something like:

<div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>

and then use navigation to get what you really want.

If you are just looking to apply styles, class names are better.

Best way to store password in database

You are correct that storing the password in a plain-text field is a horrible idea. However, as far as location goes, for most of the cases you're going to encounter (and I honestly can't think of any counter-examples) storing the representation of a password in the database is the proper thing to do. By representation I mean that you want to hash the password using a salt (which should be different for every user) and a secure 1-way algorithm and store that, throwing away the original password. Then, when you want to verify a password, you hash the value (using the same hashing algorithm and salt) and compare it to the hashed value in the database.

So, while it is a good thing you are thinking about this and it is a good question, this is actually a duplicate of these questions (at least):

To clarify a bit further on the salting bit, the danger with simply hashing a password and storing that is that if a trespasser gets a hold of your database, they can still use what are known as rainbow tables to be able to "decrypt" the password (at least those that show up in the rainbow table). To get around this, developers add a salt to passwords which, when properly done, makes rainbow attacks simply infeasible to do. Do note that a common misconception is to simply add the same unique and long string to all passwords; while this is not horrible, it is best to add unique salts to every password. Read this for more.

How to download a Nuget package without nuget.exe or Visual Studio extension?

To obtain the current stable version of the NuGet package use:

https://www.nuget.org/api/v2/package/{packageID}

Mounting multiple volumes on a docker container?

Pass multiple -v arguments.

For instance:

docker -v /on/my/host/1:/on/the/container/1 \
       -v /on/my/host/2:/on/the/container/2 \
       ...

Excel data validation with suggestions/autocomplete

I adapted the answer by ChrisB. Like in his example a temporary combobox is made visible when a cell is clicked. Additionally:

  1. List of Combobox items is updated as user types, only matching items are displayed
  2. if any item from combobox is selected, filtering is skipped as it makes sense and because of this error

_x000D_
_x000D_
Option Explicit_x000D_
_x000D_
Private Const DATA_RANGE = "A1:A16"_x000D_
Private Const DROPDOWN_RANGE = "F2:F10"_x000D_
Private Const HELP_COLUMN = "$G"_x000D_
_x000D_
_x000D_
Private Sub Worksheet_SelectionChange(ByVal target As Range)_x000D_
    Dim xWs As Worksheet_x000D_
    Set xWs = Application.ActiveSheet_x000D_
    _x000D_
    On Error Resume Next_x000D_
    _x000D_
    With Me.TempCombo_x000D_
        .LinkedCell = vbNullString_x000D_
        .Visible = False_x000D_
    End With_x000D_
    _x000D_
    If target.Cells.count > 1 Then_x000D_
        Exit Sub_x000D_
    End If_x000D_
    _x000D_
    Dim isect As Range_x000D_
    Set isect = Application.Intersect(target, Range(DROPDOWN_RANGE))_x000D_
    If isect Is Nothing Then_x000D_
       Exit Sub_x000D_
    End If_x000D_
       _x000D_
    With Me.TempCombo_x000D_
        .Visible = True_x000D_
        .Left = target.Left - 1_x000D_
        .Top = target.Top - 1_x000D_
        .Width = target.Width + 5_x000D_
        .Height = target.Height + 5_x000D_
        .LinkedCell = target.Address_x000D_
_x000D_
    End With_x000D_
_x000D_
    Me.TempCombo.Activate_x000D_
    Me.TempCombo.DropDown_x000D_
End Sub_x000D_
_x000D_
Private Sub TempCombo_Change()_x000D_
    If Me.TempCombo.Visible = False Then_x000D_
        Exit Sub_x000D_
    End If_x000D_
    _x000D_
    Dim currentValue As String_x000D_
    currentValue = Range(Me.TempCombo.LinkedCell).Value_x000D_
    _x000D_
    If Trim(currentValue & vbNullString) = vbNullString Then_x000D_
        Me.TempCombo.ListFillRange = "=" & DATA_RANGE_x000D_
    Else_x000D_
        If Me.TempCombo.ListIndex = -1 Then_x000D_
             Dim listCount As Integer_x000D_
             listCount = write_matching_items(currentValue)_x000D_
             Me.TempCombo.ListFillRange = "=" & HELP_COLUMN & "1:" & HELP_COLUMN & listCount_x000D_
             Me.TempCombo.DropDown_x000D_
        End If_x000D_
_x000D_
    End If_x000D_
End Sub_x000D_
_x000D_
_x000D_
Private Function write_matching_items(currentValue As String) As Integer_x000D_
    Dim xWs As Worksheet_x000D_
    Set xWs = Application.ActiveSheet_x000D_
_x000D_
    Dim cell As Range_x000D_
    Dim c As Range_x000D_
    Dim firstAddress As Variant_x000D_
    Dim count As Integer_x000D_
    count = 0_x000D_
    xWs.Range(HELP_COLUMN & ":" & HELP_COLUMN).Delete_x000D_
    With xWs.Range(DATA_RANGE)_x000D_
        Set c = .Find(currentValue, LookIn:=xlValues)_x000D_
        If Not c Is Nothing Then_x000D_
            firstAddress = c.Address_x000D_
            Do_x000D_
              Set cell = xWs.Range(HELP_COLUMN & "$" & (count + 1))_x000D_
              cell.Value = c.Value_x000D_
              count = count + 1_x000D_
             _x000D_
              Set c = .FindNext(c)_x000D_
              If c Is Nothing Then_x000D_
                GoTo DoneFinding_x000D_
              End If_x000D_
           Loop While c.Address <> firstAddress_x000D_
        End If_x000D_
DoneFinding:_x000D_
    End With_x000D_
    _x000D_
    write_matching_items = count_x000D_
_x000D_
End Function_x000D_
_x000D_
Private Sub TempCombo_KeyDown( __x000D_
                ByVal KeyCode As MSForms.ReturnInteger, __x000D_
                ByVal Shift As Integer)_x000D_
_x000D_
    Select Case KeyCode_x000D_
        Case 9  ' Tab key_x000D_
            Application.ActiveCell.Offset(0, 1).Activate_x000D_
        Case 13 ' Pause key_x000D_
            Application.ActiveCell.Offset(1, 0).Activate_x000D_
    End Select_x000D_
End Sub
_x000D_
_x000D_
_x000D_

Notes:

  1. ComboBoxe's MatchEntry must be set to 2 - fmMatchEntryNone. Don't forget to set ComboBox name to TempCombo
  2. I am using listFillRange to set ComboBox options. The range must be continuous, so, matching items are stored in a help column.
  3. I have tried accomplishing the same with ComboBox.addItem, but it turned out to be hard to repaint list box as user types

How to align absolutely positioned element to center?

position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

Calling async method on button click

This is what's killing you:

task.Wait();

That's blocking the UI thread until the task has completed - but the task is an async method which is going to try to get back to the UI thread after it "pauses" and awaits an async result. It can't do that, because you're blocking the UI thread...

There's nothing in your code which really looks like it needs to be on the UI thread anyway, but assuming you really do want it there, you should use:

private async void Button_Click(object sender, RoutedEventArgs 
{
    Task<List<MyObject>> task = GetResponse<MyObject>("my url");
    var items = await task;
    // Presumably use items here
}

Or just:

private async void Button_Click(object sender, RoutedEventArgs 
{
    var items = await GetResponse<MyObject>("my url");
    // Presumably use items here
}

Now instead of blocking until the task has completed, the Button_Click method will return after scheduling a continuation to fire when the task has completed. (That's how async/await works, basically.)

Note that I would also rename GetResponse to GetResponseAsync for clarity.

Remove the last chars of the Java String variable

I am surprised to see that all the other answers (as of Sep 8, 2013) either involve counting the number of characters in the substring ".null" or throw a StringIndexOutOfBoundsException if the substring is not found. Or both :(

I suggest the following:

public class Main {

    public static void main(String[] args) {

        String path = "file.txt";
        String extension = ".doc";

        int position = path.lastIndexOf(extension);

        if (position!=-1)
            path = path.substring(0, position);
        else
            System.out.println("Extension: "+extension+" not found");

        System.out.println("Result: "+path);
    }

}

If the substring is not found, nothing happens, as there is nothing to cut off. You won't get the StringIndexOutOfBoundsException. Also, you don't have to count the characters yourself in the substring.

What is a "method" in Python?

Sorry, but--in my opinion--RichieHindle is completely right about saying that method...

It's a function which is a member of a class.

Here is the example of a function that becomes the member of the class. Since then it behaves as a method of the class. Let's start with the empty class and the normal function with one argument:

>>> class C:
...     pass
...
>>> def func(self):
...     print 'func called'
...
>>> func('whatever')
func called

Now we add a member to the C class, which is the reference to the function. After that we can create the instance of the class and call its method as if it was defined inside the class:

>>> C.func = func
>>> o = C()
>>> o.func()
func called

We can use also the alternative way of calling the method:

>>> C.func(o)
func called

The o.func even manifests the same way as the class method:

>>> o.func
<bound method C.func of <__main__.C instance at 0x000000000229ACC8>>

And we can try the reversed approach. Let's define a class and steal its method as a function:

>>> class A:
...     def func(self):
...         print 'aaa'
...
>>> a = A()
>>> a.func
<bound method A.func of <__main__.A instance at 0x000000000229AD08>>
>>> a.func()
aaa

So far, it looks the same. Now the function stealing:

>>> afunc = A.func
>>> afunc(a)
aaa    

The truth is that the method does not accept 'whatever' argument:

>>> afunc('whatever')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method func() must be called with A instance as first 
  argument (got str instance instead)

IMHO, this is not the argument against method is a function that is a member of a class.

Later found the Alex Martelli's answer that basically says the same. Sorry if you consider it duplication :)

How to use ConfigurationManager

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

max value of integer

The strict equivalent of the java int is long int in C.

Edit: If int32_t is defined, then it is the equivalent in terms of precision. long int guarantee the precision of the java int, because it is guarantee to be at least 32 bits in size.

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

On Windows, I solved it by creating a pip.ini file in %APPDATA%\pip\

e.g. C:\Users\asmith\AppData\Roaming\pip\pip.ini

In the pip.ini I put the path to my certificate:

[global]
cert=C:\Users\asmith\SSL\teco-ca.crt

https://pip.pypa.io/en/stable/user_guide/#configuration has more information about the configuration file.

Comparing date part only without comparing time in JavaScript

You can use some arithmetic with the total of ms.

var date = new Date(date1);
date.setHours(0, 0, 0, 0);

var diff = date2.getTime() - date.getTime();
return diff >= 0 && diff < 86400000;

I like this because no updates to the original dates are made and perfom faster than string split and compare.

Hope this help!

Is there a way to make mv create the directory to be moved to if it doesn't exist?

rsync command can do the trick only if the last directory in the destination path doesn't exist, e.g. for the destination path of ~/bar/baz/ if bar exists but baz doesn't, then the following command can be used:

rsync -av --remove-source-files foo.c ~/bar/baz/

-a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)
-v, --verbose               increase verbosity
--remove-source-files   sender removes synchronized files (non-dir)

In this case baz directory will be created if it doesn't exist. But if both bar and baz don't exist rsync will fail:

sending incremental file list
rsync: mkdir "/root/bar/baz" failed: No such file or directory (2)
rsync error: error in file IO (code 11) at main.c(657) [Receiver=3.1.2]

So basically it should be safe to use rsync -av --remove-source-files as an alias for mv.

What are the differences between LDAP and Active Directory?

There are lots of systems that support LDAP to talk to them, not just Active Directory.

Sun, IBM, Novell all have directory services that are very effective as LDAP servers.

What is the difference between an int and an Integer in Java and C#?

Java:

int, double, long, byte, float, double, short, boolean, char - primitives. Used for hold the basic data types supported by the language. the primitive types are not part of the object hierarchy, and they do not inherit Object. Thet can'be pass by reference to a method.

Double, Float, Long, Integer, Short, Byte, Character, and Boolean, are type Wrappers, packaged in java.lang. All of the numeric type wrappers define constructors that allow an object to be constructed from a given value, or a string representation of that value. Using objects can add an overhead to even the simplest of calculations.

Beginning with JDK 5, Java has included two very helpful features: autoboxing and autounboxing. Autoboxing/unboxing greatly simplifies and streamlines code that must convert primitive types into objects, and vice versa.

Example of constructors:

Integer(int num)
Integer(String str) throws NumberFormatException
Double(double num)
Double(String str) throws NumberFormatException

Example of boxing/unboxing:

class ManualBoxing {
        public static void main(String args[]) {
        Integer objInt = new Integer(20);  // Manually box the value 20.
        int i = objInt.intValue();  // Manually unbox the value 20
        System.out.println(i + " " + iOb); // displays 20 20
    }
}

Example of autoboxing/autounboxing:

class AutoBoxing {
    public static void main(String args[]) {
        Integer objInt = 40; // autobox an int
        int i = objInt ; // auto-unbox
        System.out.println(i + " " + iOb); // displays 40 40
    }
}

P.S. Herbert Schildt's book was taken as a reference.

iPhone App Development on Ubuntu

Perhaps the best way would be to implement your app as a web app. I think you can also make web apps that run direct on the phone, without internet access or a remote server.

Web app, sounds lame? But a lot can be done with DHTML / HTML5 / JavaScript. It's a rare app that requires more power and couldn't be done as a web app. And you get pretty good cross platform with Web / JavaScript - the browsers vary a bit but a good web dev can write one web app that works pretty much everywhere.

Of course if you're writing a high-performance 3D game, the browser might not deliver what you need! maybe in a few years... Apparently some Google hackers ported Quake 2 to HTML5 already!

http://web.appstorm.net/roundups/browsers/10-html5-games-paving-the-way/

Deserialize JSON into C# dynamic object?

You can achieve that with the help of Newtonsoft.Json. Install Newtonsoft.Json from Nuget and the :

using Newtonsoft.Json;

dynamic results = JsonConvert.DeserializeObject<dynamic>(YOUR_JSON);

Case statement in MySQL

Yes, something like this:

SELECT
    id,
    action_heading,
    CASE
        WHEN action_type = 'Income' THEN action_amount
        ELSE NULL
    END AS income_amt,
    CASE
        WHEN action_type = 'Expense' THEN action_amount
        ELSE NULL
    END AS expense_amt

FROM tbl_transaction;

As other answers have pointed out, MySQL also has the IF() function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.

what is the differences between sql server authentication and windows authentication..?

Ideally, Windows authentication must be used when working in an Intranet type of an environment.

Whereas, SQL Server authentication can be used in all the other type of cases.

Here is a link which might help.

Windows Authentication vs. SQL Server Authentication

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I think that it is the Environment error,you should try setting : DJANGO_SETTINGS_MODULE='correctly_settings'

How to search if dictionary value contains certain string with Python

Klaus solution has less overhead, on the other hand this one may be more readable

myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
          'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(myDict, lookup):
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                return key

search(myDict, 'Mary')

How to use EOF to run through a text file in C?

How you detect EOF depends on what you're using to read the stream:

function                  result on EOF or error                    
--------                  ----------------------
fgets()                   NULL
fscanf()                  number of succesful conversions
                            less than expected
fgetc()                   EOF
fread()                   number of elements read
                            less than expected

Check the result of the input call for the appropriate condition above, then call feof() to determine if the result was due to hitting EOF or some other error.

Using fgets():

 char buffer[BUFFER_SIZE];
 while (fgets(buffer, sizeof buffer, stream) != NULL)
 {
   // process buffer
 }
 if (feof(stream))
 {
   // hit end of file
 }
 else
 {
   // some other error interrupted the read
 }

Using fscanf():

char buffer[BUFFER_SIZE];
while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion
{
  // process buffer
}
if (feof(stream)) 
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}

Using fgetc():

int c;
while ((c = fgetc(stream)) != EOF)
{
  // process c
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}

Using fread():

char buffer[BUFFER_SIZE];
while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1 
                                                     // element of size
                                                     // BUFFER_SIZE
{
   // process buffer
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted read
}

Note that the form is the same for all of them: check the result of the read operation; if it failed, then check for EOF. You'll see a lot of examples like:

while(!feof(stream))
{
  fscanf(stream, "%s", buffer);
  ...
}

This form doesn't work the way people think it does, because feof() won't return true until after you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.

Check if a value is an object in JavaScript

If you would like to check if the prototype for an object solely comes from Object. Filters out String, Number, Array, Arguments, etc.

function isObject (n) {
  return Object.prototype.toString.call(n) === '[object Object]';
}

Or as a single-expression arrow function (ES6+)

const isObject = n => Object.prototype.toString.call(n) === '[object Object]'

How to terminate a window in tmux?

By default
<Prefix> & for killing a window
<Prefix> x for killing a pane
And you can add config info

vi ~/.tmux.conf
bind-key X kill-session

then
<Prefix> X for killing a session

Is <div style="width: ;height: ;background: "> CSS?

For example :

_x000D_
_x000D_
<div style="height:100px; width:100px; background:#000000"></div>
_x000D_
_x000D_
_x000D_

here.

you give css to div of height and width having 100px and background as black.

PS : try to avoid inline-css you can make external CSS and import in your html file.

you can refer here for CSS

hope this helps.

SQL alias for SELECT statement

Not sure exactly what you try to denote with that syntax, but in almost all RDBMS-es you can use a subquery in the FROM clause (sometimes called an "inline-view"):

SELECT..
FROM (
     SELECT ...
     FROM ...
     ) my_select
WHERE ...

In advanced "enterprise" RDBMS-es (like oracle, SQL Server, postgresql) you can use common table expressions which allows you to refer to a query by name and reuse it even multiple times:

-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;

(example from http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx)

Display an array in a readable/hierarchical format

Very nice way to print formatted array in php, using the var_dump function.

 $a = array(1, 2, array("a", "b", "c"));
 var_dump($a);

Select folder dialog WPF

Based on Oyun's answer, it's better to use a dependency property for the FolderName. This allows (for example) binding to sub-properties, which doesn't work in the original. Also, in my adjusted version, the dialog shows selects the initial folder.

Usage in XAML:

<Button Content="...">
   <i:Interaction.Behaviors>
      <Behavior:FolderDialogBehavior FolderName="{Binding FolderPathPropertyName, Mode=TwoWay}"/>
    </i:Interaction.Behaviors>
</Button>

Code:

using System.Windows;
using System.Windows.Forms;
using System.Windows.Interactivity;
using Button = System.Windows.Controls.Button;

public class FolderDialogBehavior : Behavior<Button>
{
    #region Attached Behavior wiring
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Click += OnClick;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Click -= OnClick;
        base.OnDetaching();
    }
    #endregion

    #region FolderName Dependency Property
    public static readonly DependencyProperty FolderName =
            DependencyProperty.RegisterAttached("FolderName",
            typeof(string), typeof(FolderDialogBehavior));

    public static string GetFolderName(DependencyObject obj)
    {
        return (string)obj.GetValue(FolderName);
    }

    public static void SetFolderName(DependencyObject obj, string value)
    {
        obj.SetValue(FolderName, value);
    }
    #endregion

    private void OnClick(object sender, RoutedEventArgs e)
    {
        var dialog = new FolderBrowserDialog();
        var currentPath = GetValue(FolderName) as string;
        dialog.SelectedPath = currentPath;
        var result = dialog.ShowDialog();
        if (result == DialogResult.OK)
        {
            SetValue(FolderName, dialog.SelectedPath);
        }
    }
}

Reading a simple text file

Having a file in your assets folder requires you to use this piece of code in order to get files from the assets folder:

yourContext.getAssets().open("test.txt");

In this example, getAssets() returns an AssetManager instance and then you're free to use whatever method you want from the AssetManager API.

ADB - Android - Getting the name of the current activity

Here is a solution that is easier than the command line adb solution (which does work). It is easier because it is more graphical and can be done from within Eclipse.

In Eclipse with Android device attached go to Window menu > Show View > Other ... use filter text "Windows" to pull up Android > Windows ... show this. The top item in the list is the current activity.

Another way to pull this up is by showing the "Hierarchy View" perspective, which by default will show the Windows window.

What's the difference between window.location and document.location in JavaScript?

At least in IE, it has a little difference on local file:

document.URL will return "file://C:\projects\abc\a.html"

but window.location.href will return "file:///C:/projects/abc/a.html"

One is back slash, one is forward slash.

How to add users to Docker container?

Ubuntu

Try the following lines in Dockerfile:

RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1001 ubuntu
USER ubuntu
WORKDIR /home/ubuntu

useradd options (see: man useradd):

  • -r, --system Create a system account. see: Implications creating system accounts
  • -m, --create-home Create the user's home directory.
  • -d, --home-dir HOME_DIR Home directory of the new account.
  • -s, --shell SHELL Login shell of the new account.
  • -g, --gid GROUP Name or ID of the primary group.
  • -G, --groups GROUPS List of supplementary groups.
  • -u, --uid UID Specify user ID. see: Understanding how uid and gid work in Docker containers
  • -p, --password PASSWORD Encrypted password of the new account (e.g. ubuntu).

Setting default user's password

To set the user password, add -p "$(openssl passwd -1 ubuntu)" to useradd command.

Alternatively add the following lines to your Dockerfile:

SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN echo 'ubuntu:ubuntu' | chpasswd

The first shell instruction is to make sure that -o pipefail option is enabled before RUN with a pipe in it. Read more: Hadolint: Linting your Dockerfile.

Git - how delete file from remote repository

The easiest thing to do is to move the file from your local directory temporarily, then commit changes to your remote repo. Then add it back to your local repo, make sure to update .gitignore so it doesn't commit to remote again

Python subprocess/Popen with a modified environment

To temporarily set an environment variable without having to copy the os.envrion object etc, I do this:

process = subprocess.Popen(['env', 'RSYNC_PASSWORD=foobar', 'rsync', \
'rsync://[email protected]::'], stdout=subprocess.PIPE)

ASP.NET MVC - passing parameters to the controller

The reason for the special treatment of "id" is that it is added to the default route mapping. To change this, go to Global.asax.cs, and you will find the following line:

routes.MapRoute ("Default", "{controller}/{action}/{id}", 
                 new { controller = "Home", action = "Index", id = "" });

Change it to:

routes.MapRoute ("Default", "{controller}/{action}", 
                 new { controller = "Home", action = "Index" });

Rollback one specific migration in Laravel

better to used refresh migrate

You may rollback & re-migrate a limited number of migrations by providing the step option to the refresh command. For example, the following command will rollback & re-migrate the last two migrations:

php artisan migrate:refresh --step=2

otherwise used rollback migrate

You may rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback the last three migrations:

php artisan migrate:rollback --step=3

for more detail about migration see

Implode an array with JavaScript?

array.join was not recognizing ";" how a separator, but replacing it with comma. Using jQuery, you can use $.each to implode an array (Note that output_saved_json is the array and tmp is the string that will store the imploded array):

var tmp = "";
$.each(output_saved_json, function(index,value) {
    tmp = tmp + output_saved_json[index] + ";";
});

output_saved_json = tmp.substring(0,tmp.length - 1); // remove last ";" added

I have used substring to remove last ";" added at the final without necessity. But if you prefer, you can use instead substring something like:

var tmp = "";
$.each(output_saved_json, function(index,value) {
    tmp = tmp + output_saved_json[index];

    if((index + 1) != output_saved_json.length) {
         tmp = tmp + ";";
    }
});

output_saved_json = tmp;

I think this last solution is more slower than the 1st one because it needs to check if index is different than the lenght of array every time while $.each do not end.

How to create a multiline UITextfield?

UITextField is specifically one-line only.

Your Google search is correct, you need to use UITextView instead of UITextField for display and editing of multiline text.

In Interface Builder, add a UITextView where you want it and select the "editable" box. It will be multiline by default.

How can I get a specific field of a csv file?

#!/usr/bin/env python
"""Print a field specified by row, column numbers from given csv file.

USAGE:
    %prog csv_filename row_number column_number
"""
import csv
import sys

filename = sys.argv[1]
row_number, column_number = [int(arg, 10)-1 for arg in sys.argv[2:])]

with open(filename, 'rb') as f:
     rows = list(csv.reader(f))
     print rows[row_number][column_number]

Example

$ python print-csv-field.py input.csv 2 2
ddddd

Note: list(csv.reader(f)) loads the whole file in memory. To avoid that you could use itertools:

import itertools
# ...
with open(filename, 'rb') as f:
     row = next(itertools.islice(csv.reader(f), row_number, row_number+1))
     print row[column_number]

Visibility of global variables in imported modules

Since globals are module specific, you can add the following function to all imported modules, and then use it to:

  • Add singular variables (in dictionary format) as globals for those
  • Transfer your main module globals to it .

addglobals = lambda x: globals().update(x)

Then all you need to pass on current globals is:

import module

module.addglobals(globals())

Get skin path in Magento?

The way that Magento themes handle actual url's is as such (in view partials - phtml files):

echo $this->getSkinUrl('images/logo.png');

If you need the actual base path on disk to the image directory use:

echo Mage::getBaseDir('skin');

Some more base directory types are available in this great blog post:

http://alanstorm.com/magento_base_directories

How to sort with a lambda?

Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>

struct Foo
{
    Foo() : _i(0) {};

    int _i;

    friend std::ostream& operator<<(std::ostream& os, const Foo& f)
    {
        os << f._i;
        return os;
    };
};

typedef std::vector<Foo> VectorT;

std::string toString(const VectorT& v)
{
    std::stringstream ss;
    std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
    return ss.str();
};

int main()
{

    VectorT v(10);
    std::for_each(v.begin(), v.end(),
            [](Foo& f)
            {
                f._i = rand() % 100;
            });

    std::cout << "before sort: " << toString(v) << "\n";

    sort(v.begin(), v.end(),
            [](const Foo& a, const Foo& b)
            {
                return a._i > b._i;
            });

    std::cout << "after sort:  " << toString(v) << "\n";
    return 1;
};

The output is:

before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,

Making Python loggers output all messages to stdout in addition to log file

The simplest way to log to file and to stderr:

import logging

logging.basicConfig(filename="logfile.txt")
stderrLogger=logging.StreamHandler()
stderrLogger.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
logging.getLogger().addHandler(stderrLogger)

How to remove margin space around body or clear default css styles

try to ad the following in your CSS:

body, html{
    padding:0;
    margin:0;
}

How do I assert an Iterable contains elements with a certain property?

Try:

assertThat(myClass.getMyItems(),
                          hasItem(hasProperty("YourProperty", is("YourValue"))));

What exactly is Python's file.flush() doing?

It flushes the internal buffer, which is supposed to cause the OS to write out the buffer to the file.[1] Python uses the OS's default buffering unless you configure it do otherwise.

But sometimes the OS still chooses not to cooperate. Especially with wonderful things like write-delays in Windows/NTFS. Basically the internal buffer is flushed, but the OS buffer is still holding on to it. So you have to tell the OS to write it to disk with os.fsync() in those cases.

[1] http://docs.python.org/library/stdtypes.html

What do two question marks together mean in C#?

It's the null coalescing operator.

http://msdn.microsoft.com/en-us/library/ms173224.aspx

Yes, nearly impossible to search for unless you know what it's called! :-)

EDIT: And this is a cool feature from another question. You can chain them.

Hidden Features of C#?

How to drop all tables in a SQL Server database?

The accepted answer doesn't support Azure. It uses an undocumented stored procedure "sp_MSforeachtable". If you get an "azure could not find stored procedure 'sp_msforeachtable" error when running or simply want to avoid relying on undocumented features (which can be removed or have their functionality changed at any point) then try the below.

This version ignores the entity framework migration history table "__MigrationHistory" and the "database_firewall_rules" which is an Azure table you will not have permission to delete.

Lightly tested on Azure. Do check to make this this has no undesired effects on your environment.

DECLARE @sql NVARCHAR(2000)

WHILE(EXISTS(SELECT 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY'))
BEGIN
    SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
    EXEC(@sql)
    PRINT @sql
END

WHILE(EXISTS(SELECT * from INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'))
BEGIN
    SELECT TOP 1 @sql=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'
    EXEC(@sql)
    PRINT @sql
END

Taken from:

https://edspencer.me.uk/2013/02/25/drop-all-tables-in-a-sql-server-database-azure-friendly/

http://www.sqlservercentral.com/blogs/sqlservertips/2011/10/11/remove-all-foreign-keys/

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

How to do HTTP authentication in android?

For me, it worked,

final String basicAuth = "Basic " + Base64.encodeToString("user:password".getBytes(), Base64.NO_WRAP);

Apache HttpCLient:

request.setHeader("Authorization", basicAuth);

HttpUrlConnection:

connection.setRequestProperty ("Authorization", basicAuth);

Git will not init/sync/update new submodules

I had this same problem - it turned out that the .gitmodules file was committed, but the actual submodule commit (i.e. the record of the submodule's commit ID) wasn't.

Adding it manually seemed to do the trick - e.g.:

git submodule add http://github.com/sciyoshi/pyfacebook.git external/pyfacebook

(Even without removing anything from .git/config or .gitmodules.)

Then commit it to record the ID properly.

Adding some further comments to this working answer: If the git submodule init or git submodule update does'nt work, then as described above git submodule add url should do the trick. One can cross check this by

 git config --list

and one should get an entry of the submodule you want to pull in the result of the git config --list command. If there is an entry of your submodule in the config result, then now the usual git submodule update --init should pull your submodule. To test this step, you can manually rename the submodule and then updating the submodule.

 mv yourmodulename yourmodulename-temp
 git submodule update --init

To find out if you have local changes in the submodule, it can be seen via git status -u ( if you want to see changes in the submodule ) or git status --ignore-submodules ( if you dont want to see the changes in the submodule ).

Get the Selected value from the Drop down box in PHP

Couldn't you just pass the a name attribute and wrap it in a form?

<form id="form" action="do_stuff.php" method="post">
    <select id="select_catalog" name="select_catalog_query">
    <?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
    </select>
</form>

And then look for $_POST['select_catalog_query'] ?

Html attributes for EditorFor() in ASP.NET MVC

You can still use EditorFor. Just pass the style/whichever html attribute as ViewData.

@Html.EditorFor(model => model.YourProperty, new { style = "Width:50px" })

Because EditorFor uses templates to render, you could override the default template for your property and simply pass the style attribute as ViewData.

So your EditorTemplate would like the following:

@inherits System.Web.Mvc.WebViewPage<object>

@Html.TextBoxFor(m => m, new { @class = "text ui-widget-content", style=ViewData["style"] })

javascript: get a function's variable's value within another function

Your nameContent variable is inside the function scope and not visible outside that function so if you want to use the nameContent outside of the function then declare it global inside the <script> tag and use inside functions without the var keyword as follows

<script language="javascript" type="text/javascript">
    var nameContent; // In the global scope
    function first(){
        nameContent=document.getElementById('full_name').value;
    }

    function second() {
        first();
        y=nameContent; 
        alert(y);
    }
    second();
</script>

Interface extends another interface but implements its methods

Why does it implement its methods? How can it implement its methods when an interface can't contain method body? How can it implement the methods when it extends the other interface and not implement it? What is the purpose of an interface implementing another interface?

Interface does not implement the methods of another interface but just extends them. One example where the interface extension is needed is: consider that you have a vehicle interface with two methods moveForward and moveBack but also you need to incorporate the Aircraft which is a vehicle but with some addition methods like moveUp, moveDown so in the end you have:

public interface IVehicle {
  bool moveForward(int x);
  bool moveBack(int x);
};

and airplane:

public interface IAirplane extends IVehicle {
  bool moveDown(int x);
  bool moveUp(int x);
};

PDO get the last ID inserted

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

Like this $lid = $conn->lastInsertId();

Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue but mine was working for weeks before this. Realised I had changed my password on the server.

Remember to update your password if you've got the option selected 'Run whether user is logged on or not'

How to get config parameters in Symfony2 Twig Templates

With a Twig extension, you can create a parameterTwig function:

{{ parameter('jira_host') }}

TwigExtension.php:

class TwigExtension extends \Twig_Extension
{
    public $container;

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('parameter', function($name)
            {
                return $this->container->getParameter($name);
            })
        ];
    }


    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'iz';
    }
}

service.yml:

  iz.twig.extension:
    class: IzBundle\Services\TwigExtension
    properties:
      container: "@service_container"
    tags:
      - { name: twig.extension }

How should I store GUID in MySQL tables?

My DBA asked me when I asked about the best way to store GUIDs for my objects why I needed to store 16 bytes when I could do the same thing in 4 bytes with an Integer. Since he put that challenge out there to me I thought now was a good time to mention it. That being said...

You can store a guid as a CHAR(16) binary if you want to make the most optimal use of storage space.

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Of course:

curl http://example.com:11740
curl https://example.com:11740

Port 80 and 443 are just default port numbers.

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

I'm answering my own question because it provides a better overview of the cause and possible solutions. I've awarded the bonus to @Martin because he pin pointed the cause.

Cause

As suggested by @Martin the cause is the use of multiple threads. The request object is not available in these threads, as mentioned in the Spring Guide:

DispatcherServlet, RequestContextListener and RequestContextFilter all do exactly the same thing, namely bind the HTTP request object to the Thread that is servicing that request. This makes beans that are request- and session-scoped available further down the call chain.

Solution 1

It is possible to make the request object available to other threads, but it places a couple of limitations on the system, which may not be workable in all projects. I got this solution from Accessing request scoped beans in a multi-threaded web application:

I managed to get around this issue. I started using SimpleAsyncTaskExecutor instead of WorkManagerTaskExecutor / ThreadPoolExecutorFactoryBean. The benefit is that SimpleAsyncTaskExecutor will never re-use threads. That's only half the solution. The other half of the solution is to use a RequestContextFilter instead of RequestContextListener. RequestContextFilter (as well as DispatcherServlet) has a threadContextInheritable property which basically allows child threads to inherit the parent context.

Solution 2

The only other option is to use the session scoped bean inside the request thread. In my case this wasn't possible because:

  1. The controller method is annotated with @Async;
  2. The controller method starts a batch job which uses threads for parallel job steps.

Save a list to a .txt file

Try this, if it helps you

values = ['1', '2', '3']

with open("file.txt", "w") as output:
    output.write(str(values))

How to use nan and inf in C?

double a_nan = strtod("NaN", NULL);
double a_inf = strtod("Inf", NULL);

Algorithm to calculate the number of divisors of a given number

I don't know the MOST efficient method, but I'd do the following:

  • Create a table of primes to find all primes less than or equal to the square root of the number (Personally, I'd use the Sieve of Atkin)
  • Count all primes less than or equal to the square root of the number and multiply that by two. If the square root of the number is an integer, then subtract one from the count variable.

Should work \o/

If you need, I can code something up tomorrow in C to demonstrate.

JQuery .each() backwards

You can do

jQuery.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
}; 

followed by

$(selector).reverse().each(...) 

Make Bootstrap 3 Tabs Responsive

Pure CSS only for nav tabs, very simple for small screens:

@media (max-width: 767px) {
     .nav-tabs {
         min-width: 100%;
         display: inline-grid;
     }
}

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

I know this question was asked over 2 years ago but no one has mentioned this yet.

The best method is to use a http header

Adding the meta tag to the head doesn't always work because IE might have determined the mode before it's read. The best way to make sure IE always uses standards mode is to use a custom http header.

Header:

name: X-UA-Compatible  
value: IE=edge

For example in a .NET application you could put this in the web.config file.

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-UA-Compatible" value="IE=edge" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

LaTeX package for syntax highlighting of code in various languages

After asking a similar question I’ve created another package which uses Pygments, and offers quite a few more options than texments. It’s called minted and is quite stable and usable.

Just to show it off, here’s a code highlighted with minted:

Example code

Correct way to delete cookies server-side

Setting "expires" to a past date is the standard way to delete a cookie.

Your problem is probably because the date format is not conventional. IE probably expects GMT only.

How to read the RGB value of a given pixel in Python?

You could use the Tkinter module, which is the standard Python interface to the Tk GUI toolkit and you don't need extra download. See https://docs.python.org/2/library/tkinter.html.

(For Python 3, Tkinter is renamed to tkinter)

Here is how to set RGB values:

#from http://tkinter.unpythonic.net/wiki/PhotoImage
from Tkinter import *

root = Tk()

def pixel(image, pos, color):
    """Place pixel at pos=(x,y) on image, with color=(r,g,b)."""
    r,g,b = color
    x,y = pos
    image.put("#%02x%02x%02x" % (r,g,b), (y, x))

photo = PhotoImage(width=32, height=32)

pixel(photo, (16,16), (255,0,0))  # One lone pixel in the middle...

label = Label(root, image=photo)
label.grid()
root.mainloop()

And get RGB:

#from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py
def getRGB(image, x, y):
    value = image.get(x, y)
    return tuple(map(int, value.split(" ")))

Resource u'tokenizers/punkt/english.pickle' not found

If you're looking to only download the punkt model:

import nltk
nltk.download('punkt')

If you're unsure which data/model you need, you can install the popular datasets, models and taggers from NLTK:

import nltk
nltk.download('popular')

With the above command, there is no need to use the GUI to download the datasets.

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

A very common mistake people make is that, when they set JAVA_HOME or JRE_HOME, they set the value to C:\Program Files\Java\jdk1.8.0_221\bin or similar.

Please note JAVA_HOME and JRE_HOME value should not contain \bin

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

System.Net.WebException: The operation has timed out

Close/dispose your WebResponse object.

How to calculate the sum of the datatable column in asp.net?

You can do like..

DataRow[] dr = dtbl.Select("SUM(Amount)");
txtTotalAmount.Text = Convert.ToString(dr[0]);

How to change default text color using custom theme?

When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.

styles.xml:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
    <item name="android:editTextColor">#295055</item> 
    <item name="android:textColorPrimary">#295055</item>
    <item name="android:textColorSecondary">#295055</item>
    <item name="android:textColorTertiary">#295055</item>
    <item name="android:textColorPrimaryInverse">#295055</item>
    <item name="android:textColorSecondaryInverse">#295055</item>
    <item name="android:textColorTertiaryInverse">#295055</item>

     <item name="android:windowBackground">@drawable/custom_background</item>        
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml

The default Android style is also called “Theme”. So you calling it Theme probably confused the program.

name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

#295055 is a dark blue color.

My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

Then in Android Manifest, remember to include the code:

<application
android:theme="@style/Theme.AppBaseTheme">

get current page from url

Path.GetFileName( Request.Url.AbsolutePath )

How to remove jar file from local maven repository which was added with install:install-file?

I faced the same problem, went through all the suggestions above, but nothing worked. Finally I deleted both .m2 and .ivy folder and it worked for me.

Javascript: getFullyear() is not a function

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

How to exit git log or git diff

Add following alias in the .bashrc file

git --no-pager log --oneline -n 10
  • --no-pager will encounter the (END) word
  • -n 10 will show only the last 10 commits
  • --oneline will show the commit message, ignore the author, date information

requestFeature() must be called before adding content

I know it's over a year old, but calling requestFeature() never solved my problem. In fact I don't call it at all.

It was an issue with inflating the view I suppose. Despite all my searching, I never found a suitable solution until I played around with the different methods of inflating a view.

AlertDialog.Builder is the easy solution but requires a lot of work if you use the onPrepareDialog() to update that view.

Another alternative is to leverage AsyncTask for dialogs.

A final solution that I used is below:

public class CustomDialog extends AlertDialog {

   private View content;

   public CustomDialog(Context context) {
       super(context);

       LayoutInflater li = LayoutInflater.from(context);
       content = li.inflate(R.layout.custom_view, null);

       setUpAdditionalStuff(); // do more view cleanup
       setView(content);           
   }

   private void setUpAdditionalStuff() {
       // ...
   }

   // Call ((CustomDialog) dialog).prepare() in the onPrepareDialog() method  
   public void prepare() {
       setTitle(R.string.custom_title);
       setIcon( getIcon() );
       // ...
   }
}

* Some Additional notes:

  1. Don't rely on hiding the title. There is often an empty space despite the title not being set.
  2. Don't try to build your own View with header footer and middle view. The header, as stated above, may not be entirely hidden despite requesting FEATURE_NO_TITLE.
  3. Don't heavily style your content view with color attributes or text size. Let the dialog handle that, other wise you risk putting black text on a dark blue dialog because the vendor inverted the colors.

Establish a VPN connection in cmd

Have you looked into rasdial?

Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network

ie rasdial "VPN NETWORK NAME" "Username" *

it will then prompt for a password, else you can use "username" "password", this is however less secure

http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265

Send email with PHP from html form on submit with the same script

EDIT (#1)

If I understand correctly, you wish to have everything in one page and execute it from the same page.

You can use the following code to send mail from a single page, for example index.php or contact.php

The only difference between this one and my original answer is the <form action="" method="post"> where the action has been left blank.

It is better to use header('Location: thank_you.php'); instead of echo in the PHP handler to redirect the user to another page afterwards.

Copy the entire code below into one file.

<?php 
if(isset($_POST['submit'])){
    $to = "[email protected]"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html> 

Original answer


I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.

Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail() function.

The PHP handler will also send a copy of the message to the person who filled in the form.

You can use two forward slashes // in front of a line of code if you're not going to use it.

For example: // $subject2 = "Copy of your form submission"; will not execute.

HTML FORM:

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

PHP handler (mail_handler.php)

(Uses info from HTML form and sends the Email)

<?php 
if(isset($_POST['submit'])){
    $to = "[email protected]"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    // You cannot use header and echo together. It's one or the other.
    }
?>

To send as HTML:

If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.

Read the manual on mail() to learn how to send emails as HTML:


Footnotes:

  • In regards to HTML5

You have to specify the URL of the service that will handle the submitted data, using the action attribute.

As outlined at https://www.w3.org/TR/html5/forms.html under 4.10.1.3 Configuring a form to communicate with a server. For complete information, consult the page.

Therefore, action="" will not work in HTML5.

The proper syntax would be:

  • action="handler.xxx" or
  • action="http://www.example.com/handler.xxx".

Note that xxx will be the extension of the type of file used to handle the process. This could be a .php, .cgi, .pl, .jsp file extension etc.


Consult the following Q&A on Stack if sending mail fails:

Angular ng-repeat add bootstrap row every 3 or 4 cols

I did it only using boostrap, you must be very careful in the location of the row and the column, here is my example.

_x000D_
_x000D_
<section>_x000D_
<div class="container">_x000D_
        <div ng-app="myApp">_x000D_
        _x000D_
                <div ng-controller="SubregionController">_x000D_
                    <div class="row text-center">_x000D_
                        <div class="col-md-4" ng-repeat="post in posts">_x000D_
                            <div >_x000D_
                                <div>{{post.title}}</div>_x000D_
                            </div>_x000D_
                        </div>_x000D_
                    _x000D_
                    </div>_x000D_
                </div>        _x000D_
        </div>_x000D_
    </div>_x000D_
</div> _x000D_
_x000D_
</section>
_x000D_
_x000D_
_x000D_

Inline elements shifting when made bold on hover

_x000D_
_x000D_
li {_x000D_
    display: inline-block;_x000D_
    font-size: 0;_x000D_
}_x000D_
li a {_x000D_
    display:inline-block;_x000D_
    text-align:center;_x000D_
    font: normal 16px Arial;_x000D_
    text-transform: uppercase;_x000D_
}_x000D_
a:hover {_x000D_
    font-weight:bold;_x000D_
}_x000D_
a::before {_x000D_
    display: block;_x000D_
    content: attr(title);_x000D_
    font-weight: bold;_x000D_
    height: 0;_x000D_
    overflow: hidden;_x000D_
    visibility: hidden;_x000D_
}
_x000D_
<ul>_x000D_
    <li><a href="#" title="height">height</a></li>_x000D_
    <li><a href="#" title="icon">icon</a></li>_x000D_
    <li><a href="#" title="left">left</a></li>_x000D_
    <li><a href="#" title="letter-spacing">letter-spacing</a></li>_x000D_
    <li><a href="#" title="line-height">line-height</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Check the working example on JSfiddle. The idea is to reserve space for bolded (or any :hover state styles) content in :before pseudo element and using title tag as a source for content.

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

Concatenating strings in Razor

String.Format also works in Razor:

String.Format("{0} - {1}", Model.address, Model.city)

What is a superfast way to read large files line-by-line in VBA?

Be careful when using Application.Transpose with a huge number of values. If you transpose values to a column, excel will assume you are assuming you transposed them from rows.


Max Column Limit < Max Row Limit, and it will only display the first (Max Column Limit) values, and anithing after that will be "N/A"

Using @property versus getters and setters

Here is an excerpts from "Effective Python: 90 Specific Ways to Write Better Python" (Amazing book. I highly recommend it).

Things to Remember

? Define new class interfaces using simple public attributes and avoid defining setter and getter methods.

? Use @property to define special behavior when attributes are accessed on your objects, if necessary.

? Follow the rule of least surprise and avoid odd side effects in your @property methods.

? Ensure that @property methods are fast; for slow or complex work—especially involving I/O or causing side effects—use normal methods instead.

One advanced but common use of @property is transitioning what was once a simple numerical attribute into an on-the-fly calculation. This is extremely helpful because it lets you migrate all existing usage of a class to have new behaviors without requiring any of the call sites to be rewritten (which is especially important if there’s calling code that you don’t control). @property also provides an important stopgap for improving interfaces over time.

I especially like @property because it lets you make incremental progress toward a better data model over time.
@property is a tool to help you address problems you’ll come across in real-world code. Don’t overuse it. When you find yourself repeatedly extending @property methods, it’s probably time to refactor your class instead of further paving over your code’s poor design.

? Use @property to give existing instance attributes new functionality.

? Make incremental progress toward better data models by using @property.

? Consider refactoring a class and all call sites when you find yourself using @property too heavily.

How to include an HTML page into another HTML page without frame/iframe?

Also make sure to check out how to use Angular includes (using AngularJS). It's pretty straight forward…

<body ng-app="">
  <div ng-include="'myFile.htm'"></div>
</body> 

Preventing form resubmission

The only way to be 100% sure the same form never gets submitted twice is to embed a unique identifier in each one you issue and track which ones have been submitted at the server. The pitfall there is that if the user backs up to the page where the form was and enters new data, the same form won't work.

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

to Read More...

Getting the names of all files in a directory with PHP

Little something I created for this:

function getFiles($path) {
    if (is_dir($path)) {
        $files = scandir($path);
        $res = [];
        foreach ($files as $key => $file) {
            if ($file != "." && $file != "..") {
                array_push($res, $file);
            }
        }
        return $res;
    }
    return false;
}

Strip out HTML and Special Characters

Strip out tags, leave only alphanumeric characters and space:

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($des));

Edit: all credit to DaveRandom for the perfect solution...

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags(html_entity_decode($des)));

Using an attribute of the current class instance as a default value for method's parameter

There is much more to it than you think. Consider the defaults to be static (=constant reference pointing to one object) and stored somewhere in the definition; evaluated at method definition time; as part of the class, not the instance. As they are constant, they cannot depend on self.

Here is an example. It is counterintuitive, but actually makes perfect sense:

def add(item, s=[]):
    s.append(item)
    print len(s)

add(1)     # 1
add(1)     # 2
add(1, []) # 1
add(1, []) # 1
add(1)     # 3

This will print 1 2 1 1 3.

Because it works the same way as

default_s=[]
def add(item, s=default_s):
    s.append(item)

Obviously, if you modify default_s, it retains these modifications.

There are various workarounds, including

def add(item, s=None):
    if not s: s = []
    s.append(item)

or you could do this:

def add(self, item, s=None):
    if not s: s = self.makeDefaultS()
    s.append(item)

Then the method makeDefaultS will have access to self.

Another variation:

import types
def add(item, s=lambda self:[]):
    if isinstance(s, types.FunctionType): s = s("example")
    s.append(item)

here the default value of s is a factory function.

You can combine all these techniques:

class Foo:
    import types
    def add(self, item, s=Foo.defaultFactory):
        if isinstance(s, types.FunctionType): s = s(self)
        s.append(item)

    def defaultFactory(self):
        """ Can be overridden in a subclass, too!"""
        return []

Access elements of parent window from iframe

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

Getting the count of unique values in a column in bash

To see a frequency count for column two (for example):

awk -F '\t' '{print $2}' * | sort | uniq -c | sort -nr

fileA.txt

z    z    a
a    b    c
w    d    e

fileB.txt

t    r    e
z    d    a
a    g    c

fileC.txt

z    r    a
v    d    c
a    m    c

Result:

  3 d
  2 r
  1 z
  1 m
  1 g
  1 b

Node Multer unexpected field

probably you are not giving the same name as you mentioned in the upload.single('file') .

Check last modified date of file in C#

You simply want the File.GetLastWriteTime static method.

Example:

var lastModified = System.IO.File.GetLastWriteTime("C:\foo.bar");

Console.WriteLine(lastModified.ToString("dd/MM/yy HH:mm:ss"));

Note however that in the rare case the last-modified time is not updated by the system when writing to the file (this can happen intentionally as an optimisation for high-frequency writing, e.g. logging, or as a bug), then this approach will fail, and you will instead need to subscribe to file write notifications from the system, constantly listening.

How do I import modules or install extensions in PostgreSQL 9.1+?

Into psql terminal put:

\i <path to contrib files>

in ubuntu it usually is /usr/share/postgreslq/<your pg version>/contrib/<contrib file>.sql

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

I have enable the openssl extention and it work for me :)

;extension=php_openssl.dll

to

extension=php_openssl.dll

What's the use of "enum" in Java?

Enum serves as a type of fixed number of constants and can be used at least for two things

constant

public enum Month {
    JANUARY, FEBRUARY, ...
}

This is much better than creating a bunch of integer constants.

creating a singleton

public enum Singleton {
    INSTANCE

   // init
};

You can do quite interesting things with enums, look at here

Also look at the official documentation

How to set time to a date object in java

I should like to contribute the modern answer. This involves using java.time, the modern Java date and time API, and not the old Date nor Calendar except where there’s no way to avoid it.

Your issue is very likely really a timezone issue. When it is Tue Aug 09 00:00:00 IST 2011, in time zones west of IST midnight has not yet been reached. It is still Aug 8. If for example your API for putting the date into Excel expects UTC, the date will be the day before the one you intended. I believe the real and good solution is to produce a date-time of 00:00 UTC (or whatever time zone or offset is expected and used at the other end).

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    ZonedDateTime utcDateDime = yourDate.atStartOfDay(ZoneOffset.UTC);
    System.out.println(utcDateDime);

This prints

2018-02-27T00:00Z

Z means UTC (think of it as offset zero from UTC or Zulu time zone). Better still, of course, if you could pass the LocalDate from the first code line to Excel. It doesn’t include time-of-day, so there is no confusion possible. On the other hand, if you need an old-fashioned Date object for that, convert just before handing the Date on:

    Date oldfashionedDate = Date.from(utcDateDime.toInstant());
    System.out.println(oldfashionedDate);

On my computer this prints

Tue Feb 27 01:00:00 CET 2018

Don’t be fooled, it is correct. My time zone (Central European Time) is at offset +01:00 from UTC in February (standard time), so 01:00:00 here is equal to 00:00:00 UTC. It’s just Date.toString() grabbing the JVMs time zone and using it for producing the string.

How can I set it to something like 5:30 pm?

To answer your direct question directly, if you have a ZonedDateTime, OffsetDateTime or LocalDateTime, in all of these cases the following will accomplish what you asked for:

    yourDateTime = yourDateTime.with(LocalTime.of(17, 30));

If yourDateTime was a LocalDateTime of 2018-02-27T00:00, it will now be 2018-02-27T17:30. Similarly for the other types, only they include offset and time zone too as appropriate.

If you only had a date, as in the first snippet above, you can also add time-of-day information to it:

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    LocalDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30));

For most purposes you should prefer to add the time-of-day in a specific time zone, though, for example

    ZonedDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30))
            .atZone(ZoneId.of("Asia/Kolkata"));

This yields 2018-02-27T17:30+05:30[Asia/Kolkata].

Date and Calendar vs java.time

The Date class that you use as well as Calendar and SimpleDateFormat used in the other answers are long outdated, and SimpleDateFormat in particular has proven troublesome. In all cases the modern Java date and time API is so much nicer to work with. Which is why I wanted to provide this answer to an old question that is still being visited.

Link: Oracle Tutorial Date Time, explaining how to use java.time.

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

This question is very much answered by other people, I just want to make a point whenever deciding on any service to be in AWS is that understanding the use case for each and also see the solution that the service will provide in terms of the Well-Architected Framework, do you need High Availability, Fault Torelant, Cost optimization. This will help to decide on any kind of service to be used.

Plotting with C#

FWIW, you probably want to look at F# instead of C# in the context of technical computing because F# is specifically designed for that purpose. However, I developed my own commercial plotting library because I was not satisfied with anything freely available on .NET.

Store List to session

I found in a class file outside the scope of the Page, the above way (which I always have used) didn't work.
I found a workaround in this "context" as follows:

HttpContext.Current.Session.Add("currentUser", appUser);

and

(AppUser) HttpContext.Current.Session["currentUser"]

Otherwise the compiler was expecting a string when I pointed the object at the session object.

Iterating through a JSON object

Your loading of the JSON data is a little fragile. Instead of:

json_raw= raw.readlines()
json_object = json.loads(json_raw[0])

you should really just do:

json_object = json.load(raw)

You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0], you're asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song].

None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.

How can I solve the error LNK2019: unresolved external symbol - function?

In the Visual Studio solution tree, right click on the project 'UnitTest1', and then Add ? Existing item ? choose the file ../MyProjectTest/function.cpp.

SMTPAuthenticationError when sending mail using gmail and python

I have just sent an email with gmail through Python. Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.

So, you may get a chance with:

server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)

As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.

javascript pushing element at the beginning of an array

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);

How to center form in bootstrap 3

use centered class with offset-6 like below sample.

<body class="container">
<div class="col-lg-1 col-offset-6 centered">
    <img data-src="holder.js/100x100" alt="" />
</div>

Connection string using Windows Authentication

This is shorter and works

<connectionStrings>      
<add name="DBConnection"
             connectionString="data source=SERVER\INSTANCE;
       Initial Catalog=MyDB;Integrated Security=SSPI;"
             providerName="System.Data.SqlClient" />
</connectionStrings> 

Persist Security Info not needed

how to convert current date to YYYY-MM-DD format with angular 2

Solution in ES6/TypeScript:

let d = new Date;
console.log(d, [`${d.getFullYear()}`, `0${d.getMonth()}`.substr(-2), `0${d.getDate()}`.substr(-2)].join("-"));

git with development, staging and production branches

The thought process here is that you spend most of your time in development. When in development, you create a feature branch (off of development), complete the feature, and then merge back into development. This can then be added to the final production version by merging into production.

See A Successful Git Branching Model for more detail on this approach.

Excel VBA Macro: User Defined Type Not Defined

I am late for the party. Try replacing as below, mine worked perfectly- "DOMDocument" to "MSXML2.DOMDocument60" "XMLHTTP" to "MSXML2.XMLHTTP60"

How to serve up a JSON response using Go?

In gobuffalo.io framework I got it to work like this:

// say we are in some resource Show action
// some code is omitted
user := &models.User{}
if c.Request().Header.Get("Content-type") == "application/json" {
    return c.Render(200, r.JSON(user))
} else {
    // Make user available inside the html template
    c.Set("user", user)
    return c.Render(200, r.HTML("users/show.html"))
}

and then when I want to get JSON response for that resource I have to set "Content-type" to "application/json" and it works.

I think Rails has more convenient way to handle multiple response types, I didn't see the same in gobuffalo so far.

.NET String.Format() to add commas in thousands place for a number

The most voted answer was great and has been helpful for about 7 years. With the introduction of C# 6.0 and specifically the String Interpolation there's a neater and, IMO safer, way to do what has been asked to add commas in thousands place for a number:

var i = 5222000;
var s = $"{i:n} is the number"; // results to > 5,222,000.00 is the number
s = $"{i:n0} has no decimal"; // results to > 5,222,000 has no decimal

Where the variable i is put in place of the placeholder (i.e. {0}). So there's no need to remember which object goes to which position. The formatting (i.e. :n) hasn't changed. For a complete feature of what's new, you may go to this page.

Accessing post variables using Java Servlets

Your HttpServletRequest object has a getParameter(String paramName) method that can be used to get parameter values. http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

Old question but just had that problem /dumb jira having problems with java 10/ and didn't find a simple answer here so just gonna leave it:

$ /usr/libexec/java_home -V shows the versions installed and their locations so you can simply remove /Library/Java/JavaVirtualMachines/<the_version_you_want_to_remove>. Voila

Is it possible to reference one CSS rule within another?

You can't unless you're using some kind of extended CSS such as SASS. However it is very reasonable to apply those two extra classes to .someDiv.

If .someDiv is unique I would also choose to give it an id and referencing it in css using the id.

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

Convert a hexadecimal string to an integer efficiently in C?

For larger Hex strings like in the example I needed to use strtoul.

Jquery bind double click and single click separately

I made some changes to the above answers here which still works great: http://jsfiddle.net/arondraper/R8cDR/

Javascript: How to check if a string is empty?

if (value == "") {
  // it is empty
}

What parameters should I use in a Google Maps URL to go to a lat-lon?

All the answers didn't work for me (the loc: and @ options). So here is my solution for the new Google maps (April 2014)

Use the q= for query description, for example the street or the name of the place. Use ll= for the lat, long coordinates.

You can add extra parameters like t=h (hybrid) and z=19 (zoom)

https://maps.google.com/?q=11+wall+street+new+york&ll=40.7060471,-74.0088901

https://maps.google.com/?q=new+york+stock+exchange&ll=40.7060471,-74.0088901

https://maps.google.com/?q=new+york+stock+exchange&ll=40.7060471,-74.0088901&t=h&z=19

Angular2 @Input to a property with get/set

You could set the @Input on the setter directly, as described below:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input() set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.

PHP, Get tomorrows date from date

By strange it can seem it works perfectly fine: date_create( '2016-02-01 + 1 day' );

echo date_create( $your_date . ' + 1 day' )->format( 'Y-m-d' );

Should do it

How to make bootstrap 3 fluid layout without horizontal scrollbar

Apply to the body seems to get rid of the horizontal scrollbar

overflow-x: hidden;

Sqlite or MySql? How to decide?

The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.

How to convert string values from a dictionary, into int/float datatypes?

for sub in the_list:
    for key in sub:
        sub[key] = int(sub[key])

Gives it a casting as an int instead of as a string.

ASP.NET MVC: No parameterless constructor defined for this object

This error also occurs when using an IDependencyResolver, such as when using an IoC container, and the dependency resolver returns null. In this case ASP.NET MVC 3 defaults to using the DefaultControllerActivator to create the object. If the object being created does not have a public no-args constructor an exception will then be thrown any time the provided dependency resolver has returned null.

Here's one such stack trace:

[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67

[InvalidOperationException: An error occurred when trying to create a controller of type 'My.Namespace.MyController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
   System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
   System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963444
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

How do I wait for an asynchronously dispatched block to finish?

Very primitive solution to the problem:

void (^nextOperationAfterLongOperationBlock)(void) = ^{

};

[object runSomeLongOperationAndDo:^{
    STAssert…
    nextOperationAfterLongOperationBlock();
}];

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

I had the same problem what caused it was that I already had created a pod from the docker image via the .yml file, however I mistyped the name, i.e test-app:1.0.1 when I needed test-app:1.0.2 in my .yml file. So I did kubectl delete pods --all to remove the faulty pod then redid the kubectl create -f name_of_file.yml which solved my problem.

is of a type that is invalid for use as a key column in an index

There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
1. Set a limited size on the key field ex. nvarchar(100)
2. Create a check constraint that compares the value with all the keys in the table. The condition is:

([dbo].[CheckKey]([key])=(1))

and [dbo].[CheckKey] is a scalar function defined as:

CREATE FUNCTION [dbo].[CheckKey]
(
    @key nvarchar(max)
)
RETURNS bit
AS
BEGIN
    declare @res bit
    if exists(select * from key_value where [key] = @key)
        set @res = 0
    else
        set @res = 1

    return @res
END

But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.

Generate Row Serial Numbers in SQL Query

I found one solution for MYSQL its easy to add new column for SrNo or kind of tepropery auto increment column by following this query:

SELECT @ab:=@ab+1 as SrNo, tablename.* FROM tablename, (SELECT @ab:= 0)
AS ab

In python, what is the difference between random.uniform() and random.random()?

random.random() gives you a random floating point number in the range [0.0, 1.0) (so including 0.0, but not including 1.0 which is also known as a semi-open range). random.uniform(a, b) gives you a random floating point number in the range [a, b], (where rounding may end up giving you b).

The implementation of random.uniform() uses random.random() directly:

def uniform(self, a, b):
    "Get a random number in the range [a, b) or [a, b] depending on rounding."
    return a + (b-a) * self.random()

random.uniform(0, 1) is basically the same thing as random.random() (as 1.0 times float value closest to 1.0 still will give you float value closest to 1.0 there is no possibility of a rounding error there).

SQL Server insert if not exists best practice

Additionally, if you have multiple columns to insert and want to check if they exists or not use the following code

Insert Into [Competitors] (cName, cCity, cState)
Select cName, cCity, cState from 
(
    select new.* from 
    (
        select distinct cName, cCity, cState 
        from [Competitors] s, [City] c, [State] s
    ) new
    left join 
    (   
        select distinct cName, cCity, cState 
        from [Competitors] s
    ) existing
    on new.cName = existing.cName and new.City = existing.City and new.State = existing.State
    where existing.Name is null  or existing.City is null or existing.State is null
)

Difference between a virtual function and a pure virtual function

A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.

You denote that fact by appending the "= 0" to the declaration, like this:

class AbstractBase
{
    virtual void PureVirtualFunction() = 0;
}

Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:

class Derived : public AbstractBase
{
    virtual void PureVirtualFunction() override { }
}

By adding the override keyword, the compiler will ensure that there is a base class virtual function with the same signature.

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

Converting 'ArrayList<String> to 'String[]' in Java

In Java 8:

String[] strings = list.parallelStream().toArray(String[]::new);

Python class input argument

The problem in your initial definition of the class is that you've written:

class name(object, name):

This means that the class inherits the base class called "object", and the base class called "name". However, there is no base class called "name", so it fails. Instead, all you need to do is have the variable in the special init method, which will mean that the class takes it as a variable.

class name(object):
  def __init__(self, name):
    print name

If you wanted to use the variable in other methods that you define within the class, you can assign name to self.name, and use that in any other method in the class without needing to pass it to the method.

For example:

class name(object):
  def __init__(self, name):
    self.name = name
  def PrintName(self):
    print self.name

a = name('bob')
a.PrintName()
bob

How can you print a variable name in python?

If you are trying to do this, it means you are doing something wrong. Consider using a dict instead.

def show_val(vals, name):
    print "Name:", name, "val:", vals[name]

vals = {'a': 1, 'b': 2}
show_val(vals, 'b')

Output:

Name: b val: 2

Best way to extract a subvector from a vector?

You could just use insert

vector<type> myVec { n_elements };

vector<type> newVec;

newVec.insert(newVec.begin(), myVec.begin() + X, myVec.begin() + Y);

Unable to access JSON property with "-" dash

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]

convert string into array of integers

A quick one for modern browsers:

'14 2'.split(' ').map(Number);

// [14, 2]`

link button property to open in new tab?

Here is your Tag.

<asp:LinkButton ID="LinkButton1" runat="server">Open Test Page</asp:LinkButton>

Here is your code on the code behind.

LinkButton1.Attributes.Add("href","../Test.aspx")
LinkButton1.Attributes.Add("target","_blank")

Hope this will be helpful for someone.

Edit To do the same with a link button inside a template field, use the following code.

Use GridView_RowDataBound event to find Link button.

Dim LB as LinkButton = e.Row.FindControl("LinkButton1")         
LB.Attributes.Add("href","../Test.aspx")  
LB.Attributes.Add("target","_blank")

How many times does each value appear in a column?

I second Dave's idea. I'm not always fond of pivot tables, but in this case they are pretty straightforward to use.

Here are my results:

Enter image description here

It was so simple to create it that I have even recorded a macro in case you need to do this with VBA:

Sub Macro2()
'
' Macro2 Macro
'

'
    Range("Table1[[#All],[DATA]]").Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Table1", Version:=xlPivotTableVersion14).CreatePivotTable TableDestination _
        :="Sheet3!R3C7", TableName:="PivotTable4", DefaultVersion:= _
        xlPivotTableVersion14
    Sheets("Sheet3").Select
    Cells(3, 7).Select
    With ActiveSheet.PivotTables("PivotTable4").PivotFields("DATA")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables( _
        "PivotTable4").PivotFields("DATA"), "Count of DATA", xlCount
End Sub

HttpClient 4.0.1 - how to release connection?

To answer my own question: to release the connection (and any other resources associated with the request) you must close the InputStream returned by the HttpEntity:

InputStream is = entity.getContent();

.... process the input stream ....

is.close();       // releases all resources

From the docs

Shell script to send email

Yes it works fine and is commonly used:

$ echo "hello world" | mail -s "a subject" [email protected]

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

Java Revisited

  1. Resource included by include directive is loaded during jsp translation time, while resource included by include action is loaded during request time.
  2. Any change on included resource will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in next request.
  3. Include directive is static import, while include action is dynamic import
  4. Include directive uses file attribute to specify resource to be included while include action use page attribute for same purpose.

bootstrap responsive table content wrapping

use it in css external file.

.td-table
{
word-wrap: break-word;
word-break: break-all;  
white-space: normal !important;
text-align: justify;
}

add item in array list of android

You're trying to assign the result of the add operation to resultArrGame, and add can either return true or false, depending on if the operation was successful or not. What you want is probably just:

resultArrGame.add(txt.Game.getText().toString());

How to read single Excel cell value

Here's a solution that may work better in the case you are referencing objWorksheet.UsedRange.

Excel.Worksheet mySheet = ...(load a workbook, etc);
Excel.Range myRange = mySheet.UsedRange;
var values = (myRange.Value as Object[,]);
int rowNumber = 3, columnNumber = 5;
string cellValue = Convert.ToString(values[rowNumber, columnNumber]);

Save child objects automatically using JPA Hibernate

I tried the above but I'm getting a database error complaining that the foreign key field in the Child table can not be NULL. Is there a way to tell JPA to automatically set this foreign key into the Child object so it can automatically save children objects?

Well, there are two things here.

First, you need to cascade the save operation (but my understanding is that you are doing this or you wouldn't get a FK constraint violation during inserts in the "child" table)

Second, you probably have a bidirectional association and I think that you're not setting "both sides of the link" correctly. You are supposed to do something like this:

Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);

List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChildren(children);

session.save(parent);

A common pattern is to use link management methods:

@Entity
public class Parent {
    @Id private Long id;

    @OneToMany(mappedBy="parent")
    private List<Child> children = new ArrayList<Child>();

    ...

    protected void setChildren(List<Child> children) {
        this.children = children;
    }

    public void addToChildren(Child child) {
        child.setParent(this);
        this.children.add(child);
    }
}

And the code becomes:

Parent parent = new Parent();
...
Child c1 = new Child();
...

parent.addToChildren(c1);

session.save(parent);
References

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

How to delete a specific line in a file?

In general, you can't; you have to write the whole file again (at least from the point of change to the end).

In some specific cases you can do better than this -

if all your data elements are the same length and in no specific order, and you know the offset of the one you want to get rid of, you could copy the last item over the one to be deleted and truncate the file before the last item;

or you could just overwrite the data chunk with a 'this is bad data, skip it' value or keep a 'this item has been deleted' flag in your saved data elements such that you can mark it deleted without otherwise modifying the file.

This is probably overkill for short documents (anything under 100 KB?).

What does "Use of unassigned local variable" mean?

The compiler is saying that annualRate will not have a value if the CreditPlan is not recognised.

When creating the local variables ( annualRate, monthlyCharge, and lateFee) assign a default value (0) to them.

Also, you should display an error if the credit plan is unknown.

Eclipse doesn't stop at breakpoints

Press Ctrl + Alt + B

OR go through below steps

enter image description here

Unfortunately MyApp has stopped. How can I solve this?

Also running this command in terminal can help find the problem:

gradlew build > log.txt 2>details.txt

then you should go to gradlew file location in read two above log files.

Setting session variable using javascript

You can use

sessionStorage.SessionName = "SessionData" ,

sessionStorage.getItem("SessionName") and

sessionStorage.setItem("SessionName","SessionData");

See the supported browsers on http://caniuse.com/namevalue-storage

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

How to implement Rate It feature in Android App

AndroidRate is a library to help you promote your android app by prompting users to rate the app after using it for a few days.

Module Gradle:

dependencies {
  implementation 'com.vorlonsoft:androidrate:1.0.8'
}

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  AppRate.with(this)
      .setStoreType(StoreType.GOOGLEPLAY) //default is GOOGLEPLAY (Google Play), other options are
                                          //           AMAZON (Amazon Appstore) and
                                          //           SAMSUNG (Samsung Galaxy Apps)
      .setInstallDays((byte) 0) // default 10, 0 means install day
      .setLaunchTimes((byte) 3) // default 10
      .setRemindInterval((byte) 2) // default 1
      .setRemindLaunchTimes((byte) 2) // default 1 (each launch)
      .setShowLaterButton(true) // default true
      .setDebug(false) // default false
      //Java 8+: .setOnClickButtonListener(which -> Log.d(MainActivity.class.getName(), Byte.toString(which)))
      .setOnClickButtonListener(new OnClickButtonListener() { // callback listener.
          @Override
          public void onClickButton(byte which) {
              Log.d(MainActivity.class.getName(), Byte.toString(which));
          }
      })
      .monitor();

  if (AppRate.with(this).getStoreType() == StoreType.GOOGLEPLAY) {
      //Check that Google Play is available
      if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) != ConnectionResult.SERVICE_MISSING) {
          // Show a dialog if meets conditions
          AppRate.showRateDialogIfMeetsConditions(this);
      }
  } else {
      // Show a dialog if meets conditions
      AppRate.showRateDialogIfMeetsConditions(this);
  }
}

The default conditions to show rate dialog is as below:

  1. App is launched more than 10 days later than installation. Change via AppRate#setInstallDays(byte).
  2. App is launched more than 10 times. Change via AppRate#setLaunchTimes(byte).
  3. App is launched more than 1 days after neutral button clicked. Change via AppRate#setRemindInterval(byte).
  4. App is launched X times and X % 1 = 0. Change via AppRate#setRemindLaunchTimes(byte).
  5. App shows neutral dialog (Remind me later) by default. Change via setShowLaterButton(boolean).
  6. To specify the callback when the button is pressed. The same value as the second argument of DialogInterface.OnClickListener#onClick will be passed in the argument of onClickButton.
  7. Setting AppRate#setDebug(boolean) will ensure that the rating request is shown each time the app is launched. This feature is only for development!.

Optional custom event requirements for showing dialog

You can add additional optional requirements for showing dialog. Each requirement can be added/referenced as a unique string. You can set a minimum count for each such event (for e.g. "action_performed" 3 times, "button_clicked" 5 times, etc.)

AppRate.with(this).setMinimumEventCount(String, short);
AppRate.with(this).incrementEventCount(String);
AppRate.with(this).setEventCountValue(String, short);

Clear show dialog flag

When you want to show the dialog again, call AppRate#clearAgreeShowDialog().

AppRate.with(this).clearAgreeShowDialog();

When the button presses on

call AppRate#showRateDialog(Activity).

AppRate.with(this).showRateDialog(this);

Set custom view

call AppRate#setView(View).

LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.layout_root));
AppRate.with(this).setView(view).monitor();

Specific theme

You can use a specific theme to inflate the dialog.

AppRate.with(this).setThemeResId(int);

Custom dialog

If you want to use your own dialog labels, override string xml resources on your application.

<resources>
    <string name="rate_dialog_title">Rate this app</string>
    <string name="rate_dialog_message">If you enjoy playing this app, would you mind taking a moment to rate it? It won\'t take more than a minute. Thanks for your support!</string>
    <string name="rate_dialog_ok">Rate It Now</string>
    <string name="rate_dialog_cancel">Remind Me Later</string>
    <string name="rate_dialog_no">No, Thanks</string>
</resources>

Check that Google Play is available

if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) != ConnectionResult.SERVICE_MISSING) {

}

How to unnest a nested list

Use reduce function

reduce(lambda x, y: x + y, A, [])

Or sum

sum(A, [])

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Nicer code for this:

yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);

Initializing ArrayList with some predefined values

If you just want to initialize outside of any method then use the initializer blocks :

import java.util.ArrayList;

public class Test {
private ArrayList<String> symbolsPresent = new ArrayList<String>();

// All you need is this block.
{
symbolsPresent = new ArrayList<String>();
symbolsPresent.add("ONE");
symbolsPresent.add("TWO");
symbolsPresent.add("THREE");
symbolsPresent.add("FOUR");
}


public ArrayList<String> getSymbolsPresent() {
    return symbolsPresent;
}

public void setSymbolsPresent(ArrayList<String> symbolsPresent) {
    this.symbolsPresent = symbolsPresent;
}

public static void main(String args[]) {    
    Test t = new Test();
    System.out.println("Symbols Present is" + t.symbolsPresent);

}    
}

How can I compare two dates in PHP?

This works because of PHP's string comparison logic. Simply you can check...

if ($startdate < $date) {// do something} 
if ($startdate > $date) {// do something}

Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.

How can I select rows with most recent timestamp for each key value?

You can only select columns that are in the group or used in an aggregate function. You can use a join to get this working

select s1.* 
from sensorTable s1
inner join 
(
  SELECT sensorID, max(timestamp) as mts
  FROM sensorTable 
  GROUP BY sensorID 
) s2 on s2.sensorID = s1.sensorID and s1.timestamp = s2.mts

java.net.MalformedURLException: no protocol

The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

The method DocumentBuilder.parse(String) takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream or Reader, for example a StringReader. ... Welcome to the Java standard levels of indirections !

Basically :

DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));

Note that if you read your XML from a file, you can directly give the File object to DocumentBuilder.parse() .

As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !

How to make a div center align in HTML

it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>

for both techniques, it is imperative to set the width.

What is a clearfix?

A technique commonly used in CSS float-based layouts is assigning a handful of CSS properties to an element which you know will contain floating elements. The technique, which is commonly implemented using a class definition called clearfix, (usually) implements the following CSS behaviors:

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
    zoom: 1
}

The purpose of these combined behaviors is to create a container :after the active element containing a single '.' marked as hidden which will clear all preexisting floats and effectively reset the the page for the next piece of content.

android.app.Application cannot be cast to android.app.Activity

In my case, when I'm in an activity that extends from AppCompatActivity, it did not work(Activity) getApplicationContext (), I just putthis in its place.

Android simple alert dialog

You would simply need to do this in your onClick:

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
alertDialog.show();

I don't know from where you saw that you need DialogFragment for simply showing an alert.

Hope this helps.

Difference between PACKETS and FRAMES

A packet is a general term for a formatted unit of data carried by a network. It is not necessarily connected to a specific OSI model layer.

For example, in the Ethernet protocol on the physical layer (layer 1), the unit of data is called an "Ethernet packet", which has an Ethernet frame (layer 2) as its payload. But the unit of data of the Network layer (layer 3) is also called a "packet".

A frame is also a unit of data transmission. In computer networking the term is only used in the context of the Data link layer (layer 2).

Another semantical difference between packet and frame is that a frame envelops your payload with a header and a trailer, just like a painting in a frame, while a packet usually only has a header.

But in the end they mean roughly the same thing and the distinction is used to avoid confusion and repetition when talking about the different layers.

Find OpenCV Version Installed on Ubuntu

To install this product you can see this tutorial: OpenCV on Ubuntu

There are listed the packages you need. So, with:

# dpkg -l | grep libcv2
# dpkg -l | grep libhighgui2

and more listed in the url you can find which packages are installed.

With

# dpkg -L libcv2

you can check where are installed

This operative is used for all debian packages.

Modifying CSS class property values on the fly with JavaScript / jQuery

Demo, IE demo

You could use the following function:

function setStyle(cssText) {
    var sheet = document.createElement('style');
    sheet.type = 'text/css';
    /* Optional */ window.customSheet = sheet;
    (document.head || document.getElementsByTagName('head')[0]).appendChild(sheet);
    return (setStyle = function(cssText, node) {
        if(!node || node.parentNode !== sheet)
            return sheet.appendChild(document.createTextNode(cssText));
        node.nodeValue = cssText;
        return node;
    })(cssText);
};

Features:

  • The function is written in vanilla-js, so it has better performance than jQuery alternatives
  • One stylesheet is created after the first call to setStyle, so if you don't call it, it won't create any stylesheet.
  • The same stylesheet is reused for the following calls of setStyle
  • The function return a reference to the node associated with the bunch of CSS that you have added. If you call the function again with that node as a second argument, it will replace the old CSS with the new one.

Example

var myCSS = setStyle('*{ color:red; }');
setStyle('*{ color:blue; }', myCSS); // Replaces the previous CSS with this one

Browser support

At least, it works on IE9, FF3, Chrome 1, Safari 4, Opera 10.5.

There's also an IE version which works both on modern browsers and old versions of IE! (Works on IE8 and IE7, but can crash IE6).

Replace whitespace with a comma in a text file in Linux

tr ' ' ',' <input >output 

Substitutes each space with a comma, if you need you can make a pass with the -s flag (squeeze repeats), that replaces each input sequence of a repeated character that is listed in SET1 (the blank space) with a single occurrence of that character.

Use of squeeze repeats used to after substitute tabs:

tr -s '\t' <input | tr '\t' ',' >output 

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

you need to cast from long to int explicitly in case of i = i + l then it will compile and give correct output. like

i = i + (int)l;

or

i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.

but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.

Working with TIFFs (import, export) in Python using numpy

You could also use GDAL to do this. I realize that it is a geospatial toolkit, but nothing requires you to have a cartographic product.

Link to precompiled GDAL binaries for windows (assuming windows here) http://www.gisinternals.com/sdk/

To access the array:

from osgeo import gdal

dataset = gdal.Open("path/to/dataset.tiff", gdal.GA_ReadOnly)
for x in range(1, dataset.RasterCount + 1):
    band = dataset.GetRasterBand(x)
    array = band.ReadAsArray()

"No rule to make target 'install'"... But Makefile exists

Could you provide a whole makefile? But right now I can tell - you should check that "install" target already exists. So, check Makefile whether it contains a

install: (anything there)

line. If not, there is no such target and so make has right. Probably you should use just "make" command to compile and then use it as is or install yourself, manually.

Install is not any standard of make, it is just a common target, that could exists, but not necessary.

Bootstrap 3 Gutter Size

I tried several of the options here. For all that I tried, the spacing was uneven, or was even but when I shrank the window width enough for the subviews to stack, there was no space between stacked views.

Here is what worked for me.

.col-sm-12 { 
  margin-bottom: 2em;
}
<div class="container">
    <div class="row">
        <div class="col-sm-6">
            <div class="col-sm-12">

            </div>
        </div>
        <div class="col-sm-6">
            <div class="col-sm-12">

            </div>
        </div>
    </div>
</div>

Take nth column in a text file

If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr and/or cut or something. ...

(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)

...
while read line ; 
do 
    lineCols=( $line ) ;
    echo "${lineCols[0]}"
    echo "${lineCols[1]}"
done < $myFQFileToRead ; 
...

What is the simplest way to convert array to vector?

Personally, I quite like the C++2011 approach because it neither requires you to use sizeof() nor to remember adjusting the array bounds if you ever change the array bounds (and you can define the relevant function in C++2003 if you want, too):

#include <iterator>
#include <vector>
int x[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(std::begin(x), std::end(x));

Obviously, with C++2011 you might want to use initializer lists anyway:

std::vector<int> v({ 1, 2, 3, 4, 5 });

jQuery Cross Domain Ajax

When using "jsonp", you would basically be returning data wrapped in a function call, something like

jsonpCallback([{"id":1,"value":"testing"},{"id":2,"value":"test again"}])
where the function/callback name is 'jsonpCallback'.

If you have access to the server, please first verify that the response is in the correct "jsonp" format

For such a response coming from the server, you would need to specify something in the ajax call as well, something like

jsonpCallback: "jsonpCallback",  in your ajax call

Please note that the name of the callback does not need to be "jsonpCallback" its just a name picked as an example but it needs to match the name(wrapping) done on the server side.

My first guess to your problem is that the response from the server is not what it should be.

Best way to parse command line arguments in C#?

I like that one, because you can "define rules" for the arguments, needed or not,...

or if you're a Unix guy, than you might like the GNU Getopt .NET port.

Can I embed a custom font in an iPhone application?

I've combined some of the advice on this page into something that works for me on iOS 5.

First, you have to add the custom font to your project. Then, you need to follow the advice of @iPhoneDev and add the font to your info.plist file.

After you do that, this works:

UIFont *yourCustomFont = [UIFont fontWithName:@"YOUR-CUSTOM-FONT-POSTSCRIPT-NAME" size:14.0];
[yourUILabel setFont:yourCustomFont];

However, you need to know the Postscript name of your font. Just follow @Daniel Wood's advice and press command-i while you're in FontBook.

Then, enjoy your custom font.

Nth max salary in Oracle

Refer following query for getting nth highest salary. By this way you get nth highest salary. If you want get nth lowest salary only you need to replace DESC by ASC in the query. for getting highest salary of employee.