Programs & Examples On #Eclipse fragment

Print in one line dynamically

For those struggling as I did, I came up with the following that appears to work in both python 3.7.4 and 3.5.2.

I expanded the range from 100 to 1,000,000 because it runs very fast and you may not see the output. This is because one side effect of setting end='\r' is that the final loop iteration clears all of the output. A longer number was needed to demonstrate that it works. This result may not be desirable in all cases, but was fine in mine, and OP didn't specify one way or another. You could potentially circumvent this with an if statement that evaluates the length of the array being iterated over, etc. The key to get it working in my case was to couple the brackets "{}" with .format(). Otherwise, it didn't work.

Below should work as-is:

#!/usr/bin/env python3

for item in range(1,1000000):
    print("{}".format(item), end='\r', flush=True)

Are dictionaries ordered in Python 3.6+?

Are dictionaries ordered in Python 3.6+?

They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).

As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:

Make it so. "Dict keeps insertion order" is the ruling. Thanks!

This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.


How does the Python 3.6 dictionary implementation perform better[2] than the older one while preserving element order?

Essentially, by keeping two arrays.

  • The first array, dk_entries, holds the entries (of type PyDictKeyEntry) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).

  • The second, dk_indices, holds the indices for the dk_entries array (that is, values that indicate the position of the corresponding entry in dk_entries). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices and the corresponding entry is fetched by indexing dk_entries. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t(1 byte) to int32_t/int64_t (4/8 bytes) on 32/64 bit builds)

In the previous implementation, a sparse array of type PyDictKeyEntry and size dk_size had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size full for performance reasons. (and the empty space still had PyDictKeyEntry size!).

This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t (X depending on dict size) 2/3 * dk_sizes full is kept. The empty space changed from type PyDictKeyEntry to intX_t.

So, obviously, creating a sparse array of type PyDictKeyEntry is much more memory demanding than a sparse array for storing ints.

You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.


In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.

For example, the dictionary:

d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}

is currently stored as [keyhash, key, value]:

entries = [['--', '--', '--'],
           [-8522787127447073495, 'barry', 'green'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           [-9092791511155847987, 'timmy', 'red'],
           ['--', '--', '--'],
           [-6480567542315338377, 'guido', 'blue']]

Instead, the data should be organized as follows:

indices =  [None, 1, None, None, None, 0, None, 2]
entries =  [[-9092791511155847987, 'timmy', 'red'],
            [-8522787127447073495, 'barry', 'green'],
            [-6480567542315338377, 'guido', 'blue']]

As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.


[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==, !=). dicts currently don't offer any of those behaviors/methods.


[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.

Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.

Putting GridView data in a DataTable

Copying Grid to datatable

        if (GridView.Rows.Count != 0)
        {
            //Forloop for header
            for (int i = 0; i < GridView.HeaderRow.Cells.Count; i++)
            {
                dt.Columns.Add(GridView.HeaderRow.Cells[i].Text);
            }
            //foreach for datarow
            foreach (GridViewRow row in GridView.Rows)
            {
                DataRow dr = dt.NewRow();
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    dr[GridView.HeaderRow.Cells[j].Text] = row.Cells[j].Text;
                }
                dt.Rows.Add(dr);
            }
            //Loop for footer
            if (GridView.FooterRow.Cells.Count != 0)
            {
                DataRow dr = dt.NewRow();
                for (int i = 0; i < GridView.FooterRow.Cells.Count; i++)
                {
                    //You have to re-do the work if you did anything in databound for footer.  
                }
                dt.Rows.Add(dr);
            }
            dt.TableName = "tb";
        }

Remove HTML tags from a String

The accepted answer of doing simply Jsoup.parse(html).text() has 2 potential issues (with JSoup 1.7.3):

  • It removes line breaks from the text
  • It converts text &lt;script&gt; into <script>

If you use this to protect against XSS, this is a bit annoying. Here is my best shot at an improved solution, using both JSoup and Apache StringEscapeUtils:

// breaks multi-level of escaping, preventing &amp;lt;script&amp;gt; to be rendered as <script>
String replace = input.replace("&amp;", "");
// decode any encoded html, preventing &lt;script&gt; to be rendered as <script>
String html = StringEscapeUtils.unescapeHtml(replace);
// remove all html tags, but maintain line breaks
String clean = Jsoup.clean(html, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));
// decode html again to convert character entities back into text
return StringEscapeUtils.unescapeHtml(clean);

Note that the last step is because I need to use the output as plain text. If you need only HTML output then you should be able to remove it.

And here is a bunch of test cases (input to output):

{"regular string", "regular string"},
{"<a href=\"link\">A link</a>", "A link"},
{"<script src=\"http://evil.url.com\"/>", ""},
{"&lt;script&gt;", ""},
{"&amp;lt;script&amp;gt;", "lt;scriptgt;"}, // best effort
{"\" ' > < \n \\ é å à ü and & preserved", "\" ' > < \n \\ é å à ü and & preserved"}

If you find a way to make it better, please let me know.

Convert a Map<String, String> to a POJO

The answers provided so far using Jackson are so good, but still you could have a util function to help you convert different POJOs as follows:

    public static <T> T convert(Map<String, Object> aMap, Class<T> t) {
        try {
            return objectMapper
                    .convertValue(aMap, objectMapper.getTypeFactory().constructType(t));
        } catch (Exception e) {
            log.error("converting failed! aMap: {}, class: {}", getJsonString(aMap), t.getClass().getSimpleName(), e);
        }
        return null;
    }

Java Strings: "String s = new String("silly");"

First, you can't make a class that extends from String, because String is a final class. And java manage Strings differently from other classes so only with String you can do

String s = "Polish";

But whit your class you have to invoke the constructor. So, that code is fine.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

EncodeAndSend is not a static function, which means it can be called on an instance of the class CPMSifDlg. You cannot write this:

 CPMSifDlg::EncodeAndSend(/*...*/);  //wrong - EncodeAndSend is not static

It should rather be called as:

 CPMSifDlg dlg; //create instance, assuming it has default constructor!
 dlg.EncodeAndSend(/*...*/);   //correct 

Select top 2 rows in Hive

Here I think it's worth mentioning SORT BY and ORDER BY both clauses and why they different,

SELECT * FROM <table_name> SORT BY <column_name> DESC LIMIT 2

If you are using SORT BY clause it sort data per reducer which means if you have more than one MapReduce task it will result partially ordered data. On the other hand, the ORDER BY clause will result in ordered data for the final Reduce task. To understand more please refer to this link.

SELECT * FROM <table_name> ORDER BY <column_name> DESC LIMIT 2

Note: Finally, Even though the accepted answer contains SORT BY clause, I mostly prefer to use ORDER BY clause for the general use case to avoid any data loss.

(Excel) Conditional Formatting based on Adjacent Cell Value

You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula

=$B2>$C2

by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down

Python Serial: How to use the read or readline function to read more than 1 character at a time

Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.

You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n indicating one line.

So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n, perform your operation on the line and proceed to read the next line into the buffer.

Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...

EDIT

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
line = []

while True:
    for c in ser.read():
        line.append(c)
        if c == '\n':
            print("Line: " + ''.join(line))
            line = []
            break

ser.close()

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Small correction, unescape and escape are deprecated, so:

function utf8_to_b64( str ) {
    return window.btoa(decodeURIComponent(encodeURIComponent(str)));
}

function b64_to_utf8( str ) {
     return decodeURIComponent(encodeURIComponent(window.atob(str)));
}


function b64_to_utf8( str ) {
    str = str.replace(/\s/g, '');    
    return decodeURIComponent(encodeURIComponent(window.atob(str)));
}

Select from one table matching criteria in another?

The simplest solution would be a correlated sub select:

select
    A.*
from
    table_A A
where
    A.id in (
        select B.id from table_B B where B.tag = 'chair'
)

Alternatively you could join the tables and filter the rows you want:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

You should profile both and see which is faster on your dataset.

get the value of DisplayName attribute

Following Rich Tebb's and Matt Baker's answer, I wanted to use the ReflectionExtensions methods in a LINQ query, but it didn't work, so I've made this method for it to work.

If DisplayNameAttribute is set the method will return it, otherwise it will return the MemberInfo name.

Test method:

static void Main(string[] args)
{
    var lst = new List<Test>();
    lst.Add(new Test("coucou1", "kiki1"));
    lst.Add(new Test("coucou2", "kiki2"));
    lst.Add(new Test("coucou3", "kiki3"));
    lst.Add(new Test("coucou4", "kiki4"));
    lst.ForEach(i => 
        Console.WriteLine(i.GetAttributeName<Test>(t => t.Name) + ";" + i.GetAttributeName<Test>(t=>t.t2)));
}

Test method output:

Test method output

The class with DisplayName1 Attribute:

public class Test
{
    public Test() { }
    public Test(string name, string T2)
    {
        Name = name;
        t2 = T2;
    }
    [DisplayName("toto")]
    public string Name { get; set; }
    public string t2 { get; set; }
}

And the extension method:

public static string GetAttributeName<T>(this T itm, Expression<Func<T, object>> propertyExpression)
{
    var memberInfo = GetPropertyInformation(propertyExpression.Body);
    if (memberInfo == null)
    {
        throw new ArgumentException(
            "No property reference expression was found.",
            "propertyExpression");
    }

    var pi = typeof(T).GetProperty(memberInfo.Name);
    var ret = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().SingleOrDefault();
    return ret != null ? ret.DisplayName : pi.Name;

}

Transparent ARGB hex value

BE AWARE

In HTML/CSS (browser code) the format is #RRGGBBAA with the alpha channel as last two hexadecimal digits.

CFLAGS vs CPPFLAGS

To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:

make -p

For instance:

%.o: %.c
    $(COMPILE.c) $(OUTPUT_OPTION) $<

which expands

COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c

This will also print # environment data. Here, you will find GCC's include path among other useful info.

C_INCLUDE_PATH=/usr/include

In make, when it comes to search, the paths are many, the light is one... or something to that effect.

  1. C_INCLUDE_PATH is system-wide, set it in your shell's *.rc.
  2. $(CPPFLAGS) is for the preprocessor include path.
  3. If you need to add a general search path for make, use:
VPATH = my_dir_to_search

... or even more specific

vpath %.c src
vpath %.h include

make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.

How to make Excel VBA variables available to multiple macros?

You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules

For details on Scope of variables refer this link

Please copy the below code into any module, save the workbook and then run the code.

Here is what code does

  • The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.

  • I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.

Dim wbA As Workbook
Dim wbB As Workbook

Sub MySubRoutine()
    Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String

    folderPath = ThisWorkbook.Path & "\"
    fileNm1 = "file1.xlsx"
    fileNm2 = "file2.xlsx"

    filePath1 = folderPath & fileNm1
    filePath2 = folderPath & fileNm2

    If IsWorkBookOpen(filePath1) Then
        Set wbA = Workbooks(fileNm1)
    Else
        Set wbA = Workbooks.Open(filePath1)
    End If


    If IsWorkBookOpen(filePath2) Then
        Set wbB = Workbooks.Open(fileNm2)
    Else
        Set wbB = Workbooks.Open(filePath2)
    End If


    ' your code here
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0: IsWorkBookOpen = False
    Case 70: IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Using Prompt to select the file use below code.

Dim wbA As Workbook
Dim wbB As Workbook

Sub MySubRoutine()
    Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String

    Dim filePath As String
    cmdBrowse_Click filePath, 1

    filePath1 = filePath

    'reset the variable
    filePath = vbNullString

    cmdBrowse_Click filePath, 2
    filePath2 = filePath

   fileNm1 = GetFileName(filePath1, "\")
   fileNm2 = GetFileName(filePath2, "\")

    If IsWorkBookOpen(filePath1) Then
        Set wbA = Workbooks(fileNm1)
    Else
        Set wbA = Workbooks.Open(filePath1)
    End If


    If IsWorkBookOpen(filePath2) Then
        Set wbB = Workbooks.Open(fileNm2)
    Else
        Set wbB = Workbooks.Open(filePath2)
    End If


    ' your code here
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0: IsWorkBookOpen = False
    Case 70: IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)

    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Select workbook " & num
    fd.InitialView = msoFileDialogViewSmallIcons

    Dim FileChosen As Integer

    FileChosen = fd.Show

    fd.Filters.Clear
    fd.Filters.Add "Excel macros", "*.xlsx"


    fd.FilterIndex = 1



    If FileChosen <> -1 Then
        MsgBox "You chose cancel"
        filePath = ""
    Else
        filePath = fd.SelectedItems(1)
    End If

End Sub

Function GetFileName(fullName As String, pathSeparator As String) As String

    Dim i As Integer
    Dim iFNLenght As Integer
    iFNLenght = Len(fullName)

    For i = iFNLenght To 1 Step -1
        If Mid(fullName, i, 1) = pathSeparator Then Exit For
    Next

    GetFileName = Right(fullName, iFNLenght - i)

End Function

JAVA_HOME and PATH are set but java -version still shows the old one

Try this:

  • export JAVA_HOME=put_here_your_java_home_path
  • type export PATH=$JAVA_HOME/bin:$PATH (ensure that $JAVA_HOME is the first element in PATH)
  • try java -version

Reason: there could be other PATH elements point to alternative java home. If you put first your preferred JAVA_HOME, the system will use this one.

Do not want scientific notation on plot axis

You can use the axis() command for that, eg :

x <- 1:100000
y <- 1:100000
marks <- c(0,20000,40000,60000,80000,100000)
plot(x,y,log="x",yaxt="n",type="l")
axis(2,at=marks,labels=marks)

gives :

enter image description here

EDIT : if you want to have all of them in the same format, you can use the solution of @Richie to get them :

x <- 1:100000
y <- 1:100000
format(y,scientific=FALSE)
plot(x,y,log="x",yaxt="n",type="l")
axis(2,at=marks,labels=format(marks,scientific=FALSE))

Pagination on a list using ng-repeat

I've built a module that makes in-memory pagination incredibly simple.

It allows you to paginate by simply replacing ng-repeat with dir-paginate, specifying the items per page as a piped filter, and then dropping the controls wherever you like in the form of a single directive, <dir-pagination-controls>

To take the original example asked by Tomarto, it would look like this:

<ul class='phones'>
    <li class='thumbnail' dir-paginate='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit | itemsPerPage: limit'>
            <a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
            <a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
            <p>{{phone.snippet}}</p>
    </li>
</ul>

<dir-pagination-controls></dir-pagination-controls>

There is no need for any special pagination code in your controller. It's all handled internally by the module.

Demo: http://plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview

Source: dirPagination of GitHub

Netbeans how to set command line arguments in Java

In NetBeans IDE 8.0 you can use a community contributed plugin https://github.com/tusharvjoshi/nbrunwithargs which will allow you to pass arguments while Run Project or Run Single File command.

For passing arguments to Run Project command either you have to set the arguments in the Project properties Run panel, or use the new command available after installing the plugin which says Run with Arguments

For passing command line arguments to a Java file having main method, just right click on the method and choose Run with Arguments command, of this plugin

UPDATE (24 mar 2014) This plugin is now available in NetBeans Plugin Portal that means it can be installed from Plugins dialog box from the available plugins shown from community contributed plugins, in NetBeans IDE 8.0

Run with Arguments plugin as shown in Plugin dialog box

How to format JSON in notepad++

You have to use the plugin manager of Notepad++ and search for the JSON plugin. There you can easily install it.

This answer explains it pretty good: How to reformat JSON in Notepad++?

How is OAuth 2 different from OAuth 1?

Security of the OAuth 1.0 protocol (RFC 5849) relies on the assumption that a secret key embedded in a client application can be kept confidential. However, the assumption is naive.

In OAuth 2.0 (RFC 6749), such a naive client application is called a confidential client. On the other hand, a client application in an environment where it is difficult to keep a secret key confidential is called a public client. See 2.1. Client Types for details.

In that sense, OAuth 1.0 is a specification only for confidential clients.

"OAuth 2.0 and the Road to Hell" says that OAuth 2.0 is less secure, but there is no practical difference in security level between OAuth 1.0 clients and OAuth 2.0 confidential clients. OAuth 1.0 requires to compute signature, but it does not enhance security if it is already assured that a secret key on the client side can be kept confidential. Computing signature is just a cumbersome calculation without any practical security enhancement. I mean, compared to the simplicity that an OAuth 2.0 client connects to a server over TLS and just presents client_id and client_secret, it cannot be said that the cumbersome calculation is better in terms of security.

In addition, RFC 5849 (OAuth 1.0) does not mention anything about open redirectors while RFC 6749 (OAuth 2.0) does. That is, oauth_callback parameter of OAuth 1.0 can become a security hole.

Therefore, I don't think OAuth 1.0 is more secure than OAuth 2.0.


[April 14, 2016] Addition to clarify my point

OAuth 1.0 security relies on signature computation. A signature is computed using a secret key where a secret key is a shared key for HMAC-SHA1 (RFC 5849, 3.4.2) or a private key for RSA-SHA1 (RFC 5849, 3.4.3). Anyone who knows the secret key can compute the signature. So, if the secret key is compromised, complexity of signature computation is meaningless however complex it is.

This means OAuth 1.0 security relies not on the complexity and the logic of signature computation but merely on the confidentiality of a secret key. In other words, what is needed for OAuth 1.0 security is only the condition that a secret key can be kept confidential. This may sound extreme, but signature computation adds no security enhancement if the condition is already satisfied.

Likewise, OAuth 2.0 confidential clients rely on the same condition. If the condition is already satisfied, is there any problem in creating a secure connection using TLS and sending client_id and client_secret to an authorization server through the secured connection? Is there any big difference in security level between OAuth 1.0 and OAuth 2.0 confidential clients if both rely on the same condition?

I cannot find any good reason for OAuth 1.0 to blame OAuth 2.0. The fact is simply that (1) OAuth 1.0 is just a specification only for confidential clients and (2) OAuth 2.0 has simplified the protocol for confidential clients and supported public clients, too. Regardless of whether it is known well or not, smartphone applications are classified as public clients (RFC 6749, 9), which benefit from OAuth 2.0.

How to use a table type in a SELECT FROM statement?

You can't do it in a single query inside the package - you can't mix the SQL and PL/SQL types, and would need to define the types in the SQL layer as Tony, Marcin and Thio have said.

If you really want this done locally, and you can index the table type by VARCHAR instead of BINARY_INTEGER, you can do something like this:

-- dummy ITEM table as we don't know what the real ones looks like
create table item(
    item_num number,
    currency varchar2(9)
)
/   

insert into item values(1,'GBP');
insert into item values(2,'AUD');
insert into item values(3,'GBP');
insert into item values(4,'AUD');
insert into item values(5,'CDN');

create package so_5165580 as
    type exch_row is record(
        exch_rt_eur number,
        exch_rt_usd number);
    type exch_tbl is table of exch_row index by varchar2(9);
    exch_rt exch_tbl;
    procedure show_items;
end so_5165580;
/

create package body so_5165580 as
    procedure populate_rates is
        rate exch_row;
    begin
        rate.exch_rt_eur := 0.614394;
        rate.exch_rt_usd := 0.8494;
        exch_rt('GBP') := rate;
        rate.exch_rt_eur := 0.9817;
        rate.exch_rt_usd := 1.3572;
        exch_rt('AUD') := rate;
    end;

    procedure show_items is
        cursor c0 is
            select i.*
            from item i;
    begin
        for r0 in c0 loop
            if exch_rt.exists(r0.currency) then
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' EUR ' || exch_rt(r0.currency).exch_rt_eur
                    || ' USD ' || exch_rt(r0.currency).exch_rt_usd);
            else
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' ** no rates defined **');
            end if;
        end loop;
    end;
begin
    populate_rates;
end so_5165580;
/

So inside your loop, wherever you would have expected to use r0.exch_rt_eur you instead use exch_rt(r0.currency).exch_rt_eur, and the same for USD. Testing from an anonymous block:

begin
    so_5165580.show_items;
end;
/

Item 1 Currency GBP EUR .614394 USD .8494
Item 2 Currency AUD EUR .9817 USD 1.3572
Item 3 Currency GBP EUR .614394 USD .8494
Item 4 Currency AUD EUR .9817 USD 1.3572
Item 5 Currency CDN ** no rates defined **

Based on the answer Stef posted, this doesn't need to be in a package at all; the same results could be achieved with an insert statement. Assuming EXCH holds exchange rates of other currencies against the Euro, including USD with currency_key=1:

insert into detail_items
with rt as (select c.currency_cd as currency_cd,
        e.exch_rt as exch_rt_eur,
        (e.exch_rt / usd.exch_rt) as exch_rt_usd
    from exch e,
        currency c,
        (select exch_rt from exch where currency_key = 1) usd
    where c.currency_key = e.currency_key)
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

With items valued at 19.99 GBP and 25.00 AUD, you get detail_items:

DOC DOC_CURRENCY NET_VALUE         NET_VALUE_IN_USD  NET_VALUE_IN_EURO
--- ------------ ----------------- ----------------- -----------------
1   GBP          19.99             32.53611          23.53426
2   AUD          25                25.46041          18.41621

If you want the currency stuff to be more re-usable you could create a view:

create view rt as
select c.currency_cd as currency_cd,
    e.exch_rt as exch_rt_eur,
    (e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
    currency c,
    (select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key;

And then insert using values from that:

insert into detail_items
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

How to open a URL in a new Tab using JavaScript or jQuery?

This is as simple as this.

window.open('_link is here_', 'name'); 

Function description:

name is a name of the window. Following names are supported:

  • _blank - URL is loaded into a new tab. This is default.
  • _parent - URL is loaded into the parent frame
  • _self - URL replaces the current page
  • _top - URL replaces any framesets that may be loaded

ImportError: No module named Image

The PIL distribution is mispackaged for egg installation.

Install Pillow instead, the friendly PIL fork.

recursively use scp but excluding some folders

Although scp supports recursive directory copying with the -r option, it does not support filtering of the files. There are several ways to accomplish your task, but I would probably rely on find, xargs, tar, and ssh instead of scp.

find . -type d -wholename '*bench*/image' \
| xargs tar cf - \
| ssh user@remote tar xf - -C /my/dir

The rsync solution can be made to work, but you are missing some arguments. rsync also needs the r switch to recurse into subdirectories. Also, if you want the same security of scp, you need to do the transfer under ssh. Something like:

rsync -avr -e "ssh -l user" --exclude 'fl_*' ./bench* remote:/my/dir

The type or namespace name could not be found

The compiled dll should have public Class.

width:auto for <input> fields

Answer 1 - "response" gave a nice answer/link for it. To put it in short, "auto" is the default, so it is like removing any changes in the width of an element

Answer 2 - use width: 100% instead. It will fill the 100% of the parent container, in this case, the "form".

.Net System.Mail.Message adding multiple "To" addresses

You can do this either with multiple System.Net.Mail.MailAddress objects or you can provide a single string containing all of the addresses separated by commas

When tracing out variables in the console, How to create a new line?

You need to add the new line character \n:

console.log('line one \nline two')

would display:

line one

line two

How to get distinct values from an array of objects in JavaScript?

Simple distinct filter using Maps :

_x000D_
_x000D_
let array = 
    [
        {"name":"Joe", "age":17}, 
        {"name":"Bob", "age":17}, 
        {"name":"Carl", "age": 35}
    ];

let data = new Map();

for (let obj of array) {
  data.set(obj.age, obj);
}

let out = [...data.values()];

console.log(out);
_x000D_
_x000D_
_x000D_

How do I print out the contents of a vector?

I think the best way to do this is to just overload operator<< by adding this function to your program:

#include <vector>
using std::vector;
#include <iostream>
using std::ostream;

template<typename T>
ostream& operator<< (ostream& out, const vector<T>& v) {
    out << "{";
    size_t last = v.size() - 1;
    for(size_t i = 0; i < v.size(); ++i) {
        out << v[i];
        if (i != last) 
            out << ", ";
    }
    out << "}";
    return out;
}

Then you can use the << operator on any possible vector, assuming its elements also have ostream& operator<< defined:

vector<string>  s = {"first", "second", "third"};
vector<bool>    b = {true, false, true, false, false};
vector<int>     i = {1, 2, 3, 4};
cout << s << endl;
cout << b << endl;
cout << i << endl;

Outputs:

{first, second, third}
{1, 0, 1, 0, 0}
{1, 2, 3, 4}

Validate that a string is a positive integer

Solution 1

If we consider a JavaScript integer to be a value of maximum 4294967295 (i.e. Math.pow(2,32)-1), then the following short solution will perfectly work:

function isPositiveInteger(n) {
    return n >>> 0 === parseFloat(n);
}

DESCRIPTION:

  1. Zero-fill right shift operator does three important things:
    • truncates decimal part
      • 123.45 >>> 0 === 123
    • does the shift for negative numbers
      • -1 >>> 0 === 4294967295
    • "works" in range of MAX_INT
      • 1e10 >>> 0 === 1410065408
      • 1e7 >>> 0 === 10000000
  2. parseFloat does correct parsing of string numbers (setting NaN for non numeric strings)

TESTS:

"0"                     : true
"23"                    : true
"-10"                   : false
"10.30"                 : false
"-40.1"                 : false
"string"                : false
"1234567890"            : true
"129000098131766699.1"  : false
"-1e7"                  : false
"1e7"                   : true
"1e10"                  : false
"1edf"                  : false
" "                     : false
""                      : false

DEMO: http://jsfiddle.net/5UCy4/37/


Solution 2

Another way is good for all numeric values which are valid up to Number.MAX_VALUE, i.e. to about 1.7976931348623157e+308:

function isPositiveInteger(n) {
    return 0 === n % (!isNaN(parseFloat(n)) && 0 <= ~~n);
}

DESCRIPTION:

  1. !isNaN(parseFloat(n)) is used to filter pure string values, e.g. "", " ", "string";
  2. 0 <= ~~n filters negative and large non-integer values, e.g. "-40.1", "129000098131766699";
  3. (!isNaN(parseFloat(n)) && 0 <= ~~n) returns true if value is both numeric and positive;
  4. 0 === n % (...) checks if value is non-float -- here (...) (see 3) is evaluated as 0 in case of false, and as 1 in case of true.

TESTS:

"0"                     : true
"23"                    : true
"-10"                   : false
"10.30"                 : false
"-40.1"                 : false
"string"                : false
"1234567890"            : true
"129000098131766699.1"  : false
"-1e10"                 : false
"1e10"                  : true
"1edf"                  : false
" "                     : false
""                      : false

DEMO: http://jsfiddle.net/5UCy4/14/


The previous version:

function isPositiveInteger(n) {
    return n == "0" || ((n | 0) > 0 && n % 1 == 0);
}

DEMO: http://jsfiddle.net/5UCy4/2/

No Main class found in NetBeans

In the toolbar search for press the arrow and select Customize... It will open project properties.In the categories select RUN. Look for Main Class. Clear all the Main Class character and type your class name. Click on OK. And run again. The problem is solved.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

For those searching the internet and stumbling upon this post, I wrote a blog post on how to use the JavaScriptSerializer class.

Read more... http://procbits.com/2011/04/21/quick-json-serializationdeserialization-in-c/

Here is an example:

var json = "{\"id\":\"13\", \"value\": true}";
var jss = new JavaScriptSerializer();
var table = jss.Deserialize<dynamic>(json);
Console.WriteLine(table["id"]);
Console.WriteLine(table["value"]);

Make a nav bar stick

Just use z-index CSS property as described in the highest liked answer and the nav bar will stick to the top.

Example:

<div class="navigation">
 <nav>
   <ul>
    <li>Home</li>
    <li>Contact</li>
   </ul>
 </nav>

.navigation {
   /* fixed keyword is fine too */
   position: sticky;
   top: 0;
   z-index: 100;
   /* z-index works pretty much like a layer:
   the higher the z-index value, the greater
   it will allow the navigation tag to stay on top
   of other tags */
}

Applying Comic Sans Ms font style

The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:

http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http

810    style = "body { background-color: white; color: black; font-family: "
811        "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812        "hr { border: 0; border-bottom: 1px dashed; }\n";

E.g., try this:

font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;

Can we have multiple "WITH AS" in single sql - Oracle SQL

You can do this as:

WITH abc AS( select
             FROM ...)
, XYZ AS(select
         From abc ....) /*This one uses "abc" multiple times*/
  Select 
  From XYZ....   /*using abc, XYZ multiple times*/

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

Hey I was following the tutorial on tutorialpoint.com. Add after you complete Step 2 - Install Apache Common Logging API: You must import external jar libraries to the project from the files downloaded at this step. For me the file name was "commons-logging-1.1.1".

How to see query history in SQL Server Management Studio

you can use "Automatically generate script on every save", if you are using management studio. This is not certainly logging. Check if useful for you.. ;)

Copy file remotely with PowerShell

From PowerShell version 5 onwards (included in Windows Server 2016, downloadable as part of WMF 5 for earlier versions), this is possible with remoting. The benefit of this is that it works even if, for whatever reason, you can't access shares.

For this to work, the local session where copying is initiated must have PowerShell 5 or higher installed. The remote session does not need to have PowerShell 5 installed -- it works with PowerShell versions as low as 2, and Windows Server versions as low as 2008 R2.[1]

From server A, create a session to server B:

$b = New-PSSession B

And then, still from A:

Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt

Copying items to B is done with -ToSession. Note that local paths are used in both cases; you have to keep track of what server you're on.


[1]: when copying from or to a remote server that only has PowerShell 2, beware of this bug in PowerShell 5.1, which at the time of writing means recursive file copying doesn't work with -ToSession, an apparently copying doesn't work at all with -FromSession.

Writelines writes lines without newline, Just fills the file

The documentation for writelines() states:

writelines() does not add line separators

So you'll need to add them yourself. For example:

    line_list.append(new_line + "\n")

whenever you append a new item to line_list.

Is it possible to set the stacking order of pseudo-elements below their parent element?

There are two issues are at play here:

  1. The CSS 2.1 specification states that "The :beforeand :after pseudo-elements elements interact with other boxes, such as run-in boxes, as if they were real elements inserted just inside their associated element." Given the way z-indexes are implemented in most browsers, it's pretty difficult (read, I don't know of a way) to move content lower than the z-index of their parent element in the DOM that works in all browsers.

  2. Number 1 above does not necessarily mean it's impossible, but the second impediment to it is actually worse: Ultimately it's a matter of browser support. Firefox didn't support positioning of generated content at all until FF3.6. Who knows about browsers like IE. So even if you can find a hack to make it work in one browser, it's very likely it will only work in that browser.

The only thing I can think of that's going to work across browsers is to use javascript to insert the element rather than CSS. I know that's not a great solution, but the :before and :after pseudo-selectors just really don't look like they're gonna cut it here.

Why does viewWillAppear not get called when an app comes back from the background?

Just trying to make it as easy as possible see code below:

- (void)viewDidLoad
{
   [self appWillEnterForeground]; //register For Application Will enterForeground
}


- (id)appWillEnterForeground{ //Application will enter foreground.

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(allFunctions)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    return self;
}


-(void) allFunctions{ //call any functions that need to be run when application will enter foreground 
    NSLog(@"calling all functions...application just came back from foreground");


}

How to erase the file contents of text file in Python?

Opening a file in "write" mode clears it, you don't specifically have to write to it:

open("filename", "w").close()

(you should close it as the timing of when the file gets closed automatically may be implementation specific)

How to return a boolean method in java?

You can also do this, for readability's sake

boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());

if(!passwordVerified ){
    txtaError.setEditable(true);
    txtaError.setText("*Password didn't match!");
    txtaError.setForeground(Color.red);
    txtaError.setEditable(false);
}else{
    addNewUser();
}
return passwordVerified;

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

Best way to format integer as string with leading zeros?

Python 2.6 allows this:

add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count)

>>>add_nulls(2,3)
'002'

How to decode encrypted wordpress admin password?

You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.

There's a good howto here:

https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/

Basically:

  1. generate a new hash from a known password using e.g. http://scriptserver.mainframe8.com/wordpress_password_hasher.php, as described in the above link, or any other product that uses the phpass library,
  2. use your DB interface (e.g. phpMyAdmin) to update the user_pass field with the new hash string.

If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).

Can't find bundle for base name

If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .

How to highlight a selected row in ngRepeat?

I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.

<ul ng-repeat="vote in votes" ...>
    <li data-choice="selected" data-value="vote.id">...</li>
</ul>

Solution: http://jsfiddle.net/brandonmilleraz/5fr9V/

How to insert data using wpdb

Try this

I recently leaned about $wpdb->prepare HERE and added into our Free Class Booking plugin, plugin approved on wordpress.org and will live soon:

global $wpdb;
$tablename = $wpdb->prefix . "submitted_form";

$name     = "Kumkum"; //string value use: %s
$email    = "[email protected]"; //string value use: %s
$phone    = "3456734567"; //numeric value use: %d
$country  = "India"; //string value use: %s
$course   = "Database"; //string value use: %s
$message  = "hello i want to read db"; //string value use: %s
$now      = new DateTime(); //string value use: %s
$datesent = $now->format('Y-m-d H:i:s'); //string value use: %s

$sql = $wpdb->prepare("INSERT INTO `$tablename` (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) values (%s, %s, %d, %s, %s, %s, %s)", $name, $email, $phone, $country, $course, $message, $datesent);

$wpdb->query($sql);

Thanks -Frank

How can I concatenate a string and a number in Python?

Either something like this:

"abc" + str(9)

or

"abs{0}".format(9)

or

"abs%d" % (9,)

How can I check if a string contains a character in C#?

Use the function String.Contains();

an example call,

abs.Contains("s"); // to look for lower case s

here is more from MSDN.

how to display data values on Chart.js

Late edit: there is an official plugin for Chart.js 2.7.0+ to do this: https://github.com/chartjs/chartjs-plugin-datalabels

Original answer:

You can loop through the points / bars onAnimationComplete and display the values


Preview

enter image description here


HTML

<canvas id="myChart1" height="300" width="500"></canvas>
<canvas id="myChart2" height="300" width="500"></canvas>

Script

var chartData = {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [
        {
            fillColor: "#79D1CF",
            strokeColor: "#79D1CF",
            data: [60, 80, 81, 56, 55, 40]
        }
    ]
};

var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx).Line(chartData, {
    showTooltips: false,
    onAnimationComplete: function () {

        var ctx = this.chart.ctx;
        ctx.font = this.scale.font;
        ctx.fillStyle = this.scale.textColor
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";

        this.datasets.forEach(function (dataset) {
            dataset.points.forEach(function (points) {
                ctx.fillText(points.value, points.x, points.y - 10);
            });
        })
    }
});

var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
    showTooltips: false,
    onAnimationComplete: function () {

        var ctx = this.chart.ctx;
        ctx.font = this.scale.font;
        ctx.fillStyle = this.scale.textColor
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";

        this.datasets.forEach(function (dataset) {
            dataset.bars.forEach(function (bar) {
                ctx.fillText(bar.value, bar.x, bar.y - 5);
            });
        })
    }
});

Fiddle - http://jsfiddle.net/uh9vw0ao/

adding 1 day to a DATETIME format value

The DateTime constructor takes a parameter string time. $time can be different things, it has to respect the datetime format.

There are some valid values as examples :

  • 'now' (the default value)
  • 2017-10-19
  • 2017-10-19 11:59:59
  • 2017-10-19 +1day

So, in your case you can use the following.

$dt = new \DateTime('now +1 day'); //Tomorrow
$dt = new \DateTime('2016-01-01 +1 day'); //2016-01-02

What are the options for (keyup) in Angular2?

One like with events

(keydown)="$event.keyCode != 32 ? $event:$event.preventDefault()"

List Git aliases

Both Works Well

1 - Using Get Regex

$ git config --get-regexp alias

2 - Using list

$ git config --list | grep alias

adding noise to a signal in python

In real life you wish to simulate a signal with white noise. You should add to your signal random points that have Normal Gaussian distribution. If we speak about a device that have sensitivity given in unit/SQRT(Hz) then you need to devise standard deviation of your points from it. Here I give function "white_noise" that does this for you, an the rest of a code is demonstration and check if it does what it should.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

"""
parameters: 
rhp - spectral noise density unit/SQRT(Hz)
sr  - sample rate
n   - no of points
mu  - mean value, optional

returns:
n points of noise signal with spectral noise density of rho
"""
def white_noise(rho, sr, n, mu=0):
    sigma = rho * np.sqrt(sr/2)
    noise = np.random.normal(mu, sigma, n)
    return noise

rho = 1 
sr = 1000
n = 1000
period = n/sr
time = np.linspace(0, period, n)
signal_pure = 100*np.sin(2*np.pi*13*time)
noise = white_noise(rho, sr, n)
signal_with_noise = signal_pure + noise

f, psd = signal.periodogram(signal_with_noise, sr)

print("Mean spectral noise density = ",np.sqrt(np.mean(psd[50:])), "arb.u/SQRT(Hz)")

plt.plot(time, signal_with_noise)
plt.plot(time, signal_pure)
plt.xlabel("time (s)")
plt.ylabel("signal (arb.u.)")
plt.show()

plt.semilogy(f[1:], np.sqrt(psd[1:]))
plt.xlabel("frequency (Hz)")
plt.ylabel("psd (arb.u./SQRT(Hz))")
#plt.axvline(13, ls="dashed", color="g")
plt.axhline(rho, ls="dashed", color="r")
plt.show()

Signal with noise

PSD

How do you get the current project directory from C# code when creating a custom MSBuild task?

I know this post is very old. I was actually looking for a solution to this myself. Some of the solutions posted work but they're pretty long so I decided to write my own version.

Directory.GetParent("./../..")

Basically what it does is:

  1. . = will leave you in the same directory you are currently in.
  2. / = in this context, the directory seperator.
  3. .. = will move you one directory back (2x).
  4. GetParent() = get the parent folder of ./../..

Combining all this together will leave you with: C:\Users\Oushima\Desktop\Homework\OoP\Assignment 1\part 1, (\part 1 being my project folder).

This is what worked for me. It's very similar to .Parent.Parent but shorter. I hope this will help someone else out.

If you want it to 100% return a string datatype then you can put .FullName behind it. Oh, and, don't forget the using System.IO; C# reference.

Duplicate AssemblyVersion Attribute

In my case, there where a subfolder in a project that was a project folder it self:

  • file system:

    • c:\projects\webapi\wepapi.csproj
    • c:\projects\webapi\tests\wepapitests.csproj
  • solution

    • webapi (folder and project)
      • tests (folder)
    • tests (folder and project)

Then i had to remove the subfolder "tests" from the "webapi" project.

How to add element into ArrayList in HashMap

I know, this is an old question. But just for the sake of completeness, the lambda version.

Map<String, List<Item>> items = new HashMap<>();
items.computeIfAbsent(key, k -> new ArrayList<>()).add(item);

HttpClient - A task was cancelled?

Promoting @JobaDiniz's comment to an answer:

Do not do the obvious thing and dispose the HttpClient instance, even though the code "looks right":

async Task<HttpResponseMessage> Method() {
  using (var client = new HttpClient())
    return client.GetAsync(request);
}

The same happens with C#'s new RIAA syntax; slightly less obvious:

async Task<HttpResponseMessage> Method() {
  using var client = new HttpClient();
  return client.GetAsync(request);
}

Instead, cache a static instance of HttpClient for your app or library, and reuse it:

static HttpClient client = new HttpClient();

async Task<HttpResponseMessage> Method() {
  return client.GetAsync(request);
}

(The Async() request methods are all thread safe.)

Indent List in HTML and CSS

Normally, all lists are being displayed vertically anyways. So do you want to display it horizontally?

Anyways, you asked to override the main css file and set some css locally. You cannot do it inside <ul> with style="", that it would apply on the children (<li>).

Closest thing to locally manipulating your list would be:

<style>
    li {display: inline-block;}
</style>
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
        <li>Black tea</li>
        <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

Sending emails with Javascript

The way I'm doing it now is basically like this:

The HTML:

<textarea id="myText">
    Lorem ipsum...
</textarea>
<button onclick="sendMail(); return false">Send</button>

The Javascript:

function sendMail() {
    var link = "mailto:[email protected]"
             + "[email protected]"
             + "&subject=" + encodeURIComponent("This is my subject")
             + "&body=" + encodeURIComponent(document.getElementById('myText').value)
    ;
    
    window.location.href = link;
}

This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.

MAX function in where clause mysql

SELECT firstName, Lastname, MAX(id) as max WHERE YOUR_CONDITIONS_HERE HAVING id=max(id) 

What is a "cache-friendly" code?

Processors today work with many levels of cascading memory areas. So the CPU will have a bunch of memory that is on the CPU chip itself. It has very fast access to this memory. There are different levels of cache each one slower access ( and larger ) than the next, until you get to system memory which is not on the CPU and is relatively much slower to access.

Logically, to the CPU's instruction set you just refer to memory addresses in a giant virtual address space. When you access a single memory address the CPU will go fetch it. in the old days it would fetch just that single address. But today the CPU will fetch a bunch of memory around the bit you asked for, and copy it into the cache. It assumes that if you asked for a particular address that is is highly likely that you are going to ask for an address nearby very soon. For example if you were copying a buffer you would read and write from consecutive addresses - one right after the other.

So today when you fetch an address it checks the first level of cache to see if it already read that address into cache, if it doesn't find it, then this is a cache miss and it has to go out to the next level of cache to find it, until it eventually has to go out into main memory.

Cache friendly code tries to keep accesses close together in memory so that you minimize cache misses.

So an example would be imagine you wanted to copy a giant 2 dimensional table. It is organized with reach row in consecutive in memory, and one row follow the next right after.

If you copied the elements one row at a time from left to right - that would be cache friendly. If you decided to copy the table one column at a time, you would copy the exact same amount of memory - but it would be cache unfriendly.

Best way to reset an Oracle sequence to the next value in an existing column?

Today, in Oracle 12c or newer, you probably have the column defined as GENERATED ... AS IDENTITY, and Oracle takes care of the sequence itself.

You can use an ALTER TABLE Statement to modify "START WITH" of the identity.

ALTER TABLE tbl MODIFY ("ID" NUMBER(13,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 3580 NOT NULL ENABLE);

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

How to check for null in Twig?

you can use the following code to check whether

{% if var is defined %}

var is variable is SET

{% endif %}

Command failed due to signal: Segmentation fault: 11

For me it's because I have two bundles with the same name.

Why doesn't height: 100% work to expand divs to the screen height?

if you want, for example, a left column (height 100%) and the content (height auto) you can use absolute :

#left_column {
    float:left;
    position: absolute;
    max-height:100%;
    height:auto !important;
    height: 100%;
    overflow: hidden;

    width : 180px; /* for example */
}

#left_column div {
    height: 2000px;
}

#right_column {
    float:left;
    height:100%;
    margin-left : 180px; /* left column's width */
}

in html :

  <div id="content">
      <div id="left_column">
        my navigation content
        <div></div>
      </div>

      <div id="right_column">
        my content
      </div>
   </div>

How to replace comma (,) with a dot (.) using java

For the current information you are giving, it will be enought with this simple regex to do the replacement:

str.replaceAll(",", ".");

bootstrap datepicker today as default

For bootstrap date picker

$( ".classNmae" ).datepicker( "setDate", new Date());

* new Date is jquery default function in which you can pass custom date & if it not set, it will take current date by default

Is it bad to have my virtualenv directory inside my git repository?

Storing the virtualenv directory inside git will, as you noted, allow you to deploy the whole app by just doing a git clone (plus installing and configuring Apache/mod_wsgi). One potentially significant issue with this approach is that on Linux the full path gets hard-coded in the venv's activate, django-admin.py, easy_install, and pip scripts. This means your virtualenv won't entirely work if you want to use a different path, perhaps to run multiple virtual hosts on the same server. I think the website may actually work with the paths wrong in those files, but you would have problems the next time you tried to run pip.

The solution, already given, is to store enough information in git so that during the deploy you can create the virtualenv and do the necessary pip installs. Typically people run pip freeze to get the list then store it in a file named requirements.txt. It can be loaded with pip install -r requirements.txt. RyanBrady already showed how you can string the deploy statements in a single line:

# before 15.1.0
virtualenv --no-site-packages --distribute .env &&\
    source .env/bin/activate &&\
    pip install -r requirements.txt

# after deprecation of some arguments in 15.1.0
virtualenv .env && source .env/bin/activate && pip install -r requirements.txt

Personally, I just put these in a shell script that I run after doing the git clone or git pull.

Storing the virtualenv directory also makes it a bit trickier to handle pip upgrades, as you'll have to manually add/remove and commit the files resulting from the upgrade. With a requirements.txt file, you just change the appropriate lines in requirements.txt and re-run pip install -r requirements.txt. As already noted, this also reduces "commit spam".

from list of integers, get number closest to a given value

If we are not sure that the list is sorted, we could use the built-in min() function, to find the element which has the minimum distance from the specified number.

>>> min(myList, key=lambda x:abs(x-myNumber))
4

Note that it also works with dicts with int keys, like {1: "a", 2: "b"}. This method takes O(n) time.


If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in @Lauritz's answer which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)

Redirect form to different URL based on select option element

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

Redirect all output to file in Bash

Command:

foo >> output.txt 2>&1

appends to the output.txt file, without replacing the content.

Convert floating point number to a certain precision, and then copy to string

With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.

# Option one
older_method_string = "%.9f" % numvar

# Option two
newer_method_string = "{:.9f}".format(numvar)

But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.

For more information on option two, I suggest this link on string formatting from the Python documentation.

And for more information on option one, this link will suffice and has info on the various flags.

Python 3.6 (officially released in December of 2016), added the f string literal, see more information here, which extends the str.format method (use of curly braces such that f"{numvar:.9f}" solves the original problem), that is,

# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"

solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.

Vertical Tabs with JQuery?

Have a look at the jQuery UI vertical Tabs Docu. I try out it, it worked fine.

<style type="text/css">
/* Vertical Tabs
----------------------------------*/
.ui-tabs-vertical { width: 55em; }
.ui-tabs-vertical .ui-tabs-nav { padding: .2em .1em .2em .2em; float: left; width: 12em; }
.ui-tabs-vertical .ui-tabs-nav li { clear: left; width: 100%; border-bottom-width: 1px !important; border-right-width: 0 !important; margin: 0 -1px .2em 0; }
.ui-tabs-vertical .ui-tabs-nav li a { display:block; }
.ui-tabs-vertical .ui-tabs-nav li.ui-tabs-selected { padding-bottom: 0; padding-right: .1em; border-right-width: 1px; border-right-width: 1px; }
.ui-tabs-vertical .ui-tabs-panel { padding: 1em; float: right; width: 40em;}
</style> 

<script>
    $(document).ready(function() {
        $("#tabs").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
        $("#tabs li").removeClass('ui-corner-top').addClass('ui-corner-left');

    });
</script>

jQuery - Get Width of Element when Not Visible (Display: None)

Here is a trick I have used. It involves adding some CSS properties to make jQuery think the element is visible, but in fact it is still hidden.

var $table = $("#parent").children("table");
$table.css({ position: "absolute", visibility: "hidden", display: "block" });
var tableWidth = $table.outerWidth();
$table.css({ position: "", visibility: "", display: "" });

It is kind of a hack, but it seems to work fine for me.

UPDATE

I have since written a blog post that covers this topic. The method used above has the potential to be problematic since you are resetting the CSS properties to empty values. What if they had values previously? The updated solution uses the swap() method that was found in the jQuery source code.

Code from referenced blog post:

//Optional parameter includeMargin is used when calculating outer dimensions  
(function ($) {
$.fn.getHiddenDimensions = function (includeMargin) {
    var $item = this,
    props = { position: 'absolute', visibility: 'hidden', display: 'block' },
    dim = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
    $hiddenParents = $item.parents().andSelf().not(':visible'),
    includeMargin = (includeMargin == null) ? false : includeMargin;

    var oldProps = [];
    $hiddenParents.each(function () {
        var old = {};

        for (var name in props) {
            old[name] = this.style[name];
            this.style[name] = props[name];
        }

        oldProps.push(old);
    });

    dim.width = $item.width();
    dim.outerWidth = $item.outerWidth(includeMargin);
    dim.innerWidth = $item.innerWidth();
    dim.height = $item.height();
    dim.innerHeight = $item.innerHeight();
    dim.outerHeight = $item.outerHeight(includeMargin);

    $hiddenParents.each(function (i) {
        var old = oldProps[i];
        for (var name in props) {
            this.style[name] = old[name];
        }
    });

    return dim;
}
}(jQuery));

Drop-down box dependent on the option selected in another drop-down box

Try something like this... jsfiddle demo

HTML

<!-- Source: -->
<select id="source" name="source">
     <option>MANUAL</option>
     <option>ONLINE</option>
</select>

<!-- Status: -->
<select id="status" name="status">
    <option>OPEN</option>
    <option>DELIVERED</option>
</select>

JS

$(document).ready(function () {

    $("#source").change(function () {
        var el = $(this);
        if (el.val() === "ONLINE") {
            $("#status").append("<option>SHIPPED</option>");
        } else if (el.val() === "MANUAL") {
            $("#status option:last-child").remove();
        }
    });

});

How to share data between different threads In C# using AOP?

You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.

Read up on the lock statement.

lock

EDIT

Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.

public class Queue<T>
{
    /// <summary>Used as a lock target to ensure thread safety.</summary>
    private readonly Locker _Locker = new Locker();

    private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();

    /// <summary></summary>
    public void Enqueue(T item)
    {
        lock (_Locker)
        {
            _Queue.Enqueue(item);
        }
    }

    /// <summary>Enqueues a collection of items into this queue.</summary>
    public virtual void EnqueueRange(IEnumerable<T> items)
    {
        lock (_Locker)
        {
            if (items == null)
            {
                return;
            }

            foreach (T item in items)
            {
                _Queue.Enqueue(item);
            }
        }
    }

    /// <summary></summary>
    public T Dequeue()
    {
        lock (_Locker)
        {
            return _Queue.Dequeue();
        }
    }

    /// <summary></summary>
    public void Clear()
    {
        lock (_Locker)
        {
            _Queue.Clear();
        }
    }

    /// <summary></summary>
    public Int32 Count
    {
        get
        {
            lock (_Locker)
            {
                return _Queue.Count;
            }
        }
    }

    /// <summary></summary>
    public Boolean TryDequeue(out T item)
    {
        lock (_Locker)
        {
            if (_Queue.Count > 0)
            {
                item = _Queue.Dequeue();
                return true;
            }
            else
            {
                item = default(T);
                return false;
            }
        }
    }
}

EDIT 2

I hope this example helps. Remember this is bare bones. Using these basic ideas you can safely harness the power of threads.

public class WorkState
{
    private readonly Object _Lock = new Object();
    private Int32 _State;

    public Int32 GetState()
    {
        lock (_Lock)
        {
            return _State;
        }
    }

    public void UpdateState()
    {
        lock (_Lock)
        {
            _State++;   
        }   
    }
}

public class Worker
{
    private readonly WorkState _State;
    private readonly Thread _Thread;
    private volatile Boolean _KeepWorking;

    public Worker(WorkState state)
    {
        _State = state;
        _Thread = new Thread(DoWork);
        _KeepWorking = true;                
    }

    public void DoWork()
    {
        while (_KeepWorking)
        {
            _State.UpdateState();                   
        }
    }

    public void StartWorking()
    {
        _Thread.Start();
    }

    public void StopWorking()
    {
        _KeepWorking = false;
    }
}



private void Execute()
{
    WorkState state = new WorkState();
    Worker worker = new Worker(state);

    worker.StartWorking();

    while (true)
    {
        if (state.GetState() > 100)
        {
            worker.StopWorking();
            break;
        }
    }                   
}

Get spinner selected items text?

TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);

String subItem = textView.getText().toString();

MySQL create stored procedure syntax with delimiter

MY SQL STORED PROCEDURE CREATION

DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin

select * from users
where id=UserId ;
END $$
DELIMITER ;

Get last 30 day records from today date in SQL Server

Add one more condition in where clause

SELECT * FROM  product 
WHERE pdate >= DATEADD(day,-30,GETDATE()) 
and   pdate <= getdate()

Or use DateDiff

SELECT * FROM  product 
WHERE DATEDIFF(day,pdate,GETDATE()) between 0 and 30 

How do I add a placeholder on a CharField in Django?

Look at the widgets documentation. Basically it would look like:

q = forms.CharField(label='search', 
                    widget=forms.TextInput(attrs={'placeholder': 'Search'}))

More writing, yes, but the separation allows for better abstraction of more complicated cases.

You can also declare a widgets attribute containing a <field name> => <widget instance> mapping directly on the Meta of your ModelForm sub-class.

How do I make a column unique and index it in a Ruby on Rails migration?

Since this hasn't been mentioned yet but answers the question I had when I found this page, you can also specify that an index should be unique when adding it via t.references or t.belongs_to:

create_table :accounts do |t|
  t.references :user, index: { unique: true } # or t.belongs_to

  # other columns...
end

(as of at least Rails 4.2.7)

clear table jquery

$("#employeeTable td").parent().remove();

This will remove all tr having td as child. i.e all rows except the header will be deleted.

How to find out if a Python object is a string?

Python 2

To check if an object o is a string type of a subclass of a string type:

isinstance(o, basestring)

because both str and unicode are subclasses of basestring.

To check if the type of o is exactly str:

type(o) is str

To check if o is an instance of str or any subclass of str:

isinstance(o, str)

The above also work for Unicode strings if you replace str with unicode.

However, you may not need to do explicit type checking at all. "Duck typing" may fit your needs. See http://docs.python.org/glossary.html#term-duck-typing.

See also What’s the canonical way to check for type in python?

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

I've seen several answers and that's the only procedure that let me fix that without any conflicts.

If you want all changes from branch_new in branch_old, then:

git checkout branch_new
git merge -s ours branch_old
git checkout branch_old
git merge branch_new

once applied those four commands you can push the branch_old without any problem

Getting the client's time zone (and offset) in JavaScript

Once I had this "simple" task and I used (new Date()).getTimezoneOffset() - the approach that is widely suggested here. But it turned out that the solution wasn't quite right. For some undocumented reasons in my case new Date() was returning GMT+0200 when new Date(0) was returning GMT+0300 which was right. Since then I always use

(new Date(0)).getTimezoneOffset() to get a correct timeshift.

"Conversion to Dalvik format failed with error 1" on external JAR

Go to Project and then uncheck "Build Automatically".Then try to export the project and the error is gone.

Argument of type 'X' is not assignable to parameter of type 'X'

This problem basically comes when your compiler gets failed to understand the difference between cast operator of the type string to Number.

you can use the Number object and pass your value to get the appropriate results for it by using Number(<<<<...Variable_Name......>>>>)

Assign a synthesizable initial value to a reg in Verilog

The other answers are all good. For Xilinx FPGA designs, it is best not to use global reset lines, and use initial blocks for reset conditions for most logic. Here is the white paper from Ken Chapman (Xilinx FPGA guru)

http://japan.xilinx.com/support/documentation/white_papers/wp272.pdf

Convert a Python list with strings all to lowercase or uppercase

Besides being easier to read (for many people), list comprehensions win the speed race, too:

$ python2.6 -m timeit '[x.lower() for x in ["A","B","C"]]'
1000000 loops, best of 3: 1.03 usec per loop
$ python2.6 -m timeit '[x.upper() for x in ["a","b","c"]]'
1000000 loops, best of 3: 1.04 usec per loop

$ python2.6 -m timeit 'map(str.lower,["A","B","C"])'
1000000 loops, best of 3: 1.44 usec per loop
$ python2.6 -m timeit 'map(str.upper,["a","b","c"])'
1000000 loops, best of 3: 1.44 usec per loop

$ python2.6 -m timeit 'map(lambda x:x.lower(),["A","B","C"])'
1000000 loops, best of 3: 1.87 usec per loop
$ python2.6 -m timeit 'map(lambda x:x.upper(),["a","b","c"])'
1000000 loops, best of 3: 1.87 usec per loop

Is there a portable way to get the current username in Python?

Using only standard python libs:

from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()

Works on Windows (if you are on drive C), Mac or Linux

Alternatively, you could remove one line with an immediate invocation:

from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()

How to disable button in React.js

very simple solution for this is by using useRef hook

const buttonRef = useRef();

const disableButton = () =>{
  buttonRef.current.disabled = true; // this disables the button
 }

<button
className="btn btn-primary mt-2"
ref={buttonRef}
onClick={disableButton}
>
    Add
</button>

Similarly you can enable the button by using buttonRef.current.disabled = false

vbscript output to console

This was found on Dragon-IT Scripts and Code Repository.

You can do this with the following and stay away from the cscript/wscript differences and allows you to get the same console output that a batch file would have. This can help if your calling VBS from a batch file and need to make it look seamless.

Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."

How to avoid 'undefined index' errors?

Same idea as Michael Waterfall

From CodeIgniter

// Lets you determine whether an array index is set and whether it has a value.
// If the element is empty it returns FALSE (or whatever you specify as the default value.)
function element($item, $array, $default = FALSE)
{
    if ( ! isset($array[$item]) OR $array[$item] == "")
    {
        return $default;
    }

    return $array[$item];
}

Download an SVN repository?

Google page have a link that you can download the source code and the full tree.

Go to the Source tab, then click on Browse

then you see the link for Download it as:

How can I use interface as a C# generic type constraint?

Use an abstract class instead. So, you would have something like:

public bool Foo<T>() where T : CBase;

How to generate a random integer number from within a range

Will return a floating point number in the range [0,1]:

#define rand01() (((double)random())/((double)(RAND_MAX)))

npm - EPERM: operation not permitted on Windows

I had the same problem when I tried to install the npm package AVA. The solution for me was to delete the node_modules folder and force-clean the npm cache:

rm -rf node_modules
npm cache clean --force

I could then install the npm package without a problem.

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

Time calculation in php (add 10 hours)?

$date = date('h:i:s A', strtotime($today . ' + 10 hours'));

(untested)

how to check if List<T> element contains an item with a Particular Property Value

This is pretty easy to do using LINQ:

var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
    // Element doesn't exist
}

How do I import a pre-existing Java project into Eclipse and get up and running?

I think you'll have to import the project via the file->import wizard:

http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse

It's not the last step, but it will start you on your way.

I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

android.view.InflateException: Binary XML file: Error inflating class fragment

In my case .

The layout i was trying to inflate had

<include 
 layout  = "...."
/>

tag, removing it fixed it.

I was trying to inflate a previous layout designed for a Actvity into the view-pager adapter.

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="any" />

It won't have validation problems and the arrows will have step of "1"

Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.

The following range control only accepts values in the range 0..1, and allows 256 steps in that range:

<input name=opacity type=range min=0 max=1 step=0.00392156863>

The following control allows any time in the day to be selected, with any accuracy (e.g. thousandth-of-a-second accuracy or more):

<input name=favtime type=time step=any>

Normally, time controls are limited to an accuracy of one minute.

http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step

How to save to local storage using Flutter?

If you are in a situation where you wanna save a small value that you wanna refer later. then you should store your data as key-value data using shared_preferences

but if you want to store large data you should go with SQLITE

however you can always use firebase database which is available offline

Since we are talking about local storage you can always read and write files to the disk

Other solutions :

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

Cross domain POST request is not sending cookie Ajax Jquery

You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie header.

Are table names in MySQL case sensitive?

Table names in MySQL are file system entries, so they are case insensitive if the underlying file system is.

Anaconda version with Python 3.5

command install:

  • python3.5: conda install python=3.5
  • python3.6: conda install python=3.6

download the most recent Anaconda installer:

  • python3.5: Anaconda 4.2.0
  • python3.6: Anaconda 5.2.0

reference from anaconda doc:

ASP.NET Background image

1) Use a CSS stylesheet - add <link rel="stylesheet" type="text/css" href="styles.css" /> to include it.

2) Apply the background to the body:

body {
    background-image:url('images/background.png');
    background-repeat:no-repeat;
    background-attachment:fixed;
}

See:

http://www.w3schools.com/css/css_howto.asp

http://www.w3schools.com/cssref/pr_background-position.asp

How to stop VBA code running?

This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).

As Microsoft states:

Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).

Here is an illustrative example:

Sub RunSomeMacros()

    Call FirstPart
    Call SecondPart

    'the below code will not be executed if user clicks yes during SecondPart.
    Call ThirdPart
    MsgBox "All of the macros have been run."

End Sub

Private Sub FirstPart()
    MsgBox "This is the first macro"

End Sub

Private Sub SecondPart()
    Dim answer As Long
    answer = MsgBox("Do you want to stop the macros?", vbYesNo)

    If answer = vbYes Then
        'Stops All macros!
        End
    End If

    MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub

Private Sub ThirdPart()
    MsgBox "Final Macro was run."
End Sub

Is there a C++ gdb GUI for Linux?

Have you ever taken a look at DS-5 debugger?

There is a paid version which includes a lot of helpful features, but you can also use Community Edition for free (which is also quite useful especially for embedded systems).

I have a positive experience with this tool when debugging Android applications on real device using eclipse.

Change Timezone in Lumen or Laravel 5

Just changing APP_TIMEZONE=Asia/Colombo in .env and run php artisan lumen-config:cache worked for me in lumen 5.7

Check if input value is empty and display an alert

Better one is here.

$('#submit').click(function()
{
    if( !$('#myMessage').val() ) {
       alert('warning');
    }
});

And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

$('#submit').on('click',function()
{
    if( $('#myMessage').val().length === 0 ) {
        alert('warning');
    }
});

If you're sure it will always operate on a textfield element then you can just use this.value.

$('#submit').click(function()
{
      if( !document.getElementById('myMessage').value ) {
          alert('warning');
      }
});

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).

How do I connect to a Websphere Datasource with a given JNDI name?

Find below code to get database connection from your web app server. Just create datasource in app server and use following code to get connection :

// To Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/abcd");
// Get Connection and Statement
Connection c = ds.getConnection();
stmt = c.createStatement();

Import naming and sql classes. No need to add any xml file or to edit anything in project.
That's it..

Npm install cannot find module 'semver'

Start fresh.

brew uninstall --force node
brew install node

ValueError: unsupported format character while forming strings

For anyone checking this using python 3:

If you want to print the following output "100% correct":

python 3.8: print("100% correct")
python 3.7 and less: print("100%% correct")


A neat programming workaround for compatibility across diff versions of python is shown below:

Note: If you have to use this, you're probably experiencing many other errors... I'd encourage you to upgrade / downgrade python in relevant machines so that they are all compatible.

DevOps is a notable exception to the above -- implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.

import sys

if version_info.major==3:
    if version_info.minor>=8:
        my_string = "100% correct"
    else:
        my_string = "100%% correct"

# Finally
print(my_string)

Unable to compile simple Java 10 / Java 11 project with Maven

Alright so for me nothing worked.
I was using spring boot with hibernate. The spring boot version was ~2.0.1 and I would keep get this error and null pointer exception upon compilation. The issue was with hibernate that needed a version bump. But after that I had some other issues that seemed like the annotation processor was not recognised so I decided to just bump spring from 2.0.1 to 2.1.7-release and everything worked as expected.

You still need to add the above plugin tough
Hope it helps!

How to read a string one letter at a time in python

Use 'index'.

def GetMorseCode(letter):
   index = letterList.index(letter)
   code = codeList[index]
   return code

Of course, you'll want to validate your input letter (convert its case as necessary, make sure it's in the list in the first place by checking that index != -1), but that should get you down the path.

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

How to write a simple Java program that finds the greatest common divisor between two numbers?

One way to do it is the code below:

        int gcd = 0;
        while (gcdNum2 !=0 && gcdNum1 != 0 ) {
        if(gcdNum1 % gcdNum2 == 0){
            gcd = gcdNum2;
        }
            int aux = gcdNum2; 
            gcdNum2 = gcdNum1 % gcdNum2;
            gcdNum1 = aux;
    }

You do not need recursion to do this.

And be careful, it says that when a number is zero, then the GCD is the number that is not zero.

    while (gcdNum1 == 0) {
    gcdNum1 = 0;
}

You should modify this to fulfill the requirement.

I am not going to tell you how to modify your code entirely, only how to calculate the gcd.

How should I store GUID in MySQL tables?

char(36) would be a good choice. Also MySQL's UUID() function can be used which returns a 36-character text format (hex with hyphens) which can be used for retrievals of such IDs from the db.

C++ - Assigning null to a std::string

Literal 0 is of type int and you can't assign int to std::string. Use mValue.clear() or assign an empty string mValue="".

How to make CSS3 rounded corners hide overflow in Chrome/Opera

I found another solution for this problem. This looks like another bug in WebKit (or probably Chrome), but it works. All you need to do - is to add a WebKit CSS Mask to the #wrapper element. You can use a single pixel png image and even include it to the CSS to save a HTTP request.

#wrapper {
width: 300px; height: 300px;
border-radius: 100px;
overflow: hidden;
position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */

/* this fixes the overflow:hidden in Chrome */
-webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
}

#box {
width: 300px; height: 300px;
background-color: #cde;
}?

JSFiddle Example

How do I read a date in Excel format in Python?

excel stores dates and times as a number representing the number of days since 1900-Jan-0, if you want to get the dates in date format using python, just subtract 2 days from the days column, as shown below:

Date = sheet.cell(1,0).value-2 //in python

at column 1 in my excel, i have my date and above command giving me date values minus 2 days, which is same as date present in my excel sheet

Pointer to incomplete class type is not allowed

Check out if you are missing some import.

How does the "this" keyword work?

Since this thread has bumped up, I have compiled few points for readers new to this topic.

How is the value of this determined?

We use this similar to the way we use pronouns in natural languages like English: “John is running fast because he is trying to catch the train.” Instead we could have written “… John is trying to catch the train”.

var person = {    
    firstName: "Penelope",
    lastName: "Barrymore",
    fullName: function () {

    // We use "this" just as in the sentence above:
       console.log(this.firstName + " " + this.lastName);

    // We could have also written:
       console.log(person.firstName + " " + person.lastName);
    }
}

this is not assigned a value until an object invokes the function where it is defined. In the global scope, all global variables and functions are defined on the window object. Therefore, this in a global function refers to (and has the value of) the global window object.

When use strict, this in global and in anonymous functions that are not bound to any object holds a value of undefined.

The this keyword is most misunderstood when: 1) we borrow a method that uses this, 2) we assign a method that uses this to a variable, 3) a function that uses this is passed as a callback function, and 4) this is used inside a closure — an inner function. (2)

table

What holds the future

Defined in ECMA Script 6, arrow-functions adopt the this binding from the enclosing (function or global) scope.

function foo() {
     // return an arrow function
     return (a) => {
     // `this` here is lexically inherited from `foo()`
     console.log(this.a);
  };
}
var obj1 = { a: 2 };
var obj2 = { a: 3 };

var bar = foo.call(obj1);
bar.call( obj2 ); // 2, not 3!

While arrow-functions provide an alternative to using bind(), it’s important to note that they essentially are disabling the traditional this mechanism in favor of more widely understood lexical scoping. (1)


References:

  1. this & Object Prototypes, by Kyle Simpson. © 2014 Getify Solutions.
  2. javascriptissexy.com - http://goo.gl/pvl0GX
  3. Angus Croll - http://goo.gl/Z2RacU

More elegant way of declaring multiple variables at the same time

I like the top voted answer; however, it has problems with list as shown.

  >> a, b = ([0]*5,)*2
  >> print b
  [0, 0, 0, 0, 0]
  >> a[0] = 1
  >> print b
  [1, 0, 0, 0, 0]

This is discussed in great details (here), but the gist is that a and b are the same object with a is b returning True (same for id(a) == id(b)). Therefore if you change an index, you are changing the index of both a and b, since they are linked. To solve this you can do (source)

>> a, b = ([0]*5 for i in range(2))
>> print b
[0, 0, 0, 0, 0]
>> a[0] = 1
>> print b
[0, 0, 0, 0, 0]

This can then be used as a variant of the top answer, which has the "desired" intuitive results

>> a, b, c, d, e, g, h, i = (True for i in range(9))
>> f = (False for i in range(1)) #to be pedantic

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

How can I turn a List of Lists into a List in Java 8?

The flatMap method on Stream can certainly flatten those lists for you, but it must create Stream objects for element, then a Stream for the result.

You don't need all those Stream objects. Here is the simple, concise code to perform the task.

// listOfLists is a List<List<Object>>.
List<Object> result = new ArrayList<>();
listOfLists.forEach(result::addAll);

Because a List is Iterable, this code calls the forEach method (Java 8 feature), which is inherited from Iterable.

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified.

And a List's Iterator returns items in sequential order.

For the Consumer, this code passes in a method reference (Java 8 feature) to the pre-Java 8 method List.addAll to add the inner list elements sequentially.

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation).

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

add to your global file this action.

protected void Application_Start() {
   BundleConfig.RegisterBundles(BundleTable.Bundles);
}

open the file upload dialogue box onclick the image

HTML Code:

 <form method="post" action="#" id="#">
<div class="form-group files color">
    <input type="file" class="form-control" multiple="">
</div>

CSS:

.files input {
outline: 2px dashed #92b0b3;
outline-offset: -10px;
-webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
transition: outline-offset .15s ease-in-out, background-color .15s linear;
padding: 120px 0px 85px 35%;
text-align: center !important;
margin: 0;
width: 100% !important;
height: 400px;

}

.files input:focus{    
    outline: 2px dashed #92b0b3; 
    outline-offset: -10px;
   -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
    transition: outline-offset .15s ease-in-out, background-color .15s linear;
  border:1px solid #92b0b3;

}

.files{ position:relative}
   .files:after {  pointer-events: none;
     position: absolute;
     top: 60px;
     left: 0;
    width: 50px;
   right: 0;
   height: 400px;
  content: "";
  background-image: url('../../images/');
  display: block;
  margin: 0 auto;
  background-size: 100%;
  background-repeat: no-repeat;

}

.color input{ background-color:#f1f1f1;}
.files:before {
  position: absolute;
  bottom: 10px;
   left: 0;  pointer-events: none;
  width: 100%;
  right: 0;
  height: 400px;
  display: block;
  margin: 0 auto;
  color: #2ea591;
  font-weight: 600;
  text-transform: capitalize;
  text-align: center;

}

How to get selenium to wait for ajax response?

A more general solution than waiting for an element would be to wait for all the connections to the server to close. This will allow you to wait for all ajax calls to finish, even if they don't have any callback and thus don't affect the page. More details can be found here.

Using C# and jQuery, I have created the following method to wait for all AJax calls to complete (if anyone have more direct ways of accessing JS variables from C#, please comment):

internal void WaitForAjax(int timeOut = 15)
{
    var value = "";
    RepeatUntil(
        () => value = GetJavascriptValue("jQuery.active"), 
        () => value == "0", 
        "Ajax calls did not complete before timeout"
    );
}

internal void RepeatUntil(Action repeat, Func<bool> until, string errorMessage, int timeout = 15)
{
    var end = DateTime.Now + TimeSpan.FromSeconds(timeout);
    var complete = false;

    while (DateTime.Now < end)
    {
        repeat();
        try
        {
            if (until())
            {
                complete = true;
                break;
            }
        }
        catch (Exception)
        { }
        Thread.Sleep(500);
    }
    if (!complete)
        throw new TimeoutException(errorMessage);
}

internal string GetJavascriptValue(string variableName)
{
    var id = Guid.NewGuid().ToString();
    _selenium.RunScript(String.Format(@"window.$('body').append(""<input type='text' value='""+{0}+""' id='{1}'/>"");", variableName, id));
    return _selenium.GetValue(id);
}

How to count lines in a document?

I just made a program to do this ( with node )

npm install gimme-lines
gimme-lines verbose --exclude=node_modules,public,vendor --exclude_extensions=html

https://github.com/danschumann/gimme-lines/tree/master

Creating instance list of different objects

I believe your best shot is to declare the list as a list of objects:

List<Object> anything = new ArrayList<Object>();

Then you can put whatever you want in it, like:

anything.add(new Employee(..))

Evidently, you will not be able to read anything out of the list without a proper casting:

Employee mike = (Employee) anything.get(0);

I would discourage the use of raw types like:

List anything = new ArrayList()

Since the whole purpose of generics is precisely to avoid them, in the future Java may no longer suport raw types, the raw types are considered legacy and once you use a raw type you are not allowed to use generics at all in a given reference. For instance, take a look a this another question: Combining Raw Types and Generic Methods

OPTION (RECOMPILE) is Always Faster; Why?

To add to the excellent list (given by @CodeCowboyOrg) of situations where OPTION(RECOMPILE) can be very helpful,

  1. Table Variables. When you are using table variables, there will not be any pre-built statistics for the table variable, often leading to large differences between estimated and actual rows in the query plan. Using OPTION(RECOMPILE) on queries with table variables allows generation of a query plan that has a much better estimate of the row numbers involved. I had a particularly critical use of a table variable that was unusable, and which I was going to abandon, until I added OPTION(RECOMPILE). The run time went from hours to just a few minutes. That is probably unusual, but in any case, if you are using table variables and working on optimizing, it's well worth seeing whether OPTION(RECOMPILE) makes a difference.

Return anonymous type results?

You can return anonymous types, but it really isn't pretty.

In this case I think it would be far better to create the appropriate type. If it's only going to be used from within the type containing the method, make it a nested type.

Personally I'd like C# to get "named anonymous types" - i.e. the same behaviour as anonymous types, but with names and property declarations, but that's it.

EDIT: Others are suggesting returning dogs, and then accessing the breed name via a property path etc. That's a perfectly reasonable approach, but IME it leads to situations where you've done a query in a particular way because of the data you want to use - and that meta-information is lost when you just return IEnumerable<Dog> - the query may be expecting you to use (say) Breed rather than Ownerdue to some load options etc, but if you forget that and start using other properties, your app may work but not as efficiently as you'd originally envisaged. Of course, I could be talking rubbish, or over-optimising, etc...

How do I import a .dmp file into Oracle?

i got solution what you are getting as per imp help=y it is mentioned that imp is only valid for TRANSPORT_TABLESPACE as below:

Keyword  Description (Default)       Keyword      Description (Default)
--------------------------------------------------------------------------
USERID   username/password           FULL         import entire file (N)
BUFFER   size of data buffer         FROMUSER     list of owner usernames
FILE     input files (EXPDAT.DMP)    TOUSER       list of usernames
SHOW     just list file contents (N) TABLES       list of table names
IGNORE   ignore create errors (N)    RECORDLENGTH length of IO record
GRANTS   import grants (Y)           INCTYPE      incremental import type
INDEXES  import indexes (Y)          COMMIT       commit array insert (N)
ROWS     import data rows (Y)        PARFILE      parameter filename
LOG      log file of screen output   CONSTRAINTS  import constraints (Y)
DESTROY                overwrite tablespace data file (N)
INDEXFILE              write table/index info to specified file
SKIP_UNUSABLE_INDEXES  skip maintenance of unusable indexes (N)
FEEDBACK               display progress every x rows(0)
TOID_NOVALIDATE        skip validation of specified type ids
FILESIZE               maximum size of each dump file
STATISTICS             import precomputed statistics (always)
RESUMABLE              suspend when a space related error is encountered(N)
RESUMABLE_NAME         text string used to identify resumable statement
RESUMABLE_TIMEOUT      wait time for RESUMABLE
COMPILE                compile procedures, packages, and functions (Y)
STREAMS_CONFIGURATION  import streams general metadata (Y)
STREAMS_INSTANTIATION  import streams instantiation metadata (N)
DATA_ONLY              import only data (N)

The following keywords only apply to transportable tablespaces
TRANSPORT_TABLESPACE import transportable tablespace metadata (N)
TABLESPACES tablespaces to be transported into database
DATAFILES datafiles to be transported into database
TTS_OWNERS users that own data in the transportable tablespace set

So, Please create table space for your user:

CREATE TABLESPACE <tablespace name> DATAFILE <path to save, example: 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\ABC.dbf'> SIZE 100M AUTOEXTEND ON NEXT 100M MAXSIZE 10G EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;

Parsing CSV files in C#, with header

Another one to this list, Cinchoo ETL - an open source library to read and write multiple file formats (CSV, flat file, Xml, JSON etc)

Sample below shows how to read CSV file quickly (No POCO object required)

string csv = @"Id, Name
1, Carl
2, Tom
3, Mark";

using (var p = ChoCSVReader.LoadText(csv)
    .WithFirstLineHeader()
    )
{
    foreach (var rec in p)
    {
        Console.WriteLine($"Id: {rec.Id}");
        Console.WriteLine($"Name: {rec.Name}");
    }
}

Sample below shows how to read CSV file using POCO object

public partial class EmployeeRec
{
    public int Id { get; set; }
    public string Name { get; set; }
}

static void CSVTest()
{
    string csv = @"Id, Name
1, Carl
2, Tom
3, Mark";

    using (var p = ChoCSVReader<EmployeeRec>.LoadText(csv)
        .WithFirstLineHeader()
        )
    {
        foreach (var rec in p)
        {
            Console.WriteLine($"Id: {rec.Id}");
            Console.WriteLine($"Name: {rec.Name}");
        }
    }
}

Please check out articles at CodeProject on how to use it.

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

How do I detect when someone shakes an iPhone?

I came across this post looking for a "shaking" implementation. millenomi's answer worked well for me, although i was looking for something that required a bit more "shaking action" to trigger. I've replaced to Boolean value with an int shakeCount. I also reimplemented the L0AccelerationIsShaking() method in Objective-C. You can tweak the ammount of shaking required by tweaking the ammount added to shakeCount. I'm not sure i've found the optimal values yet, but it seems to be working well so far. Hope this helps someone:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    if (self.lastAcceleration) {
        if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) {
            //Shaking here, DO stuff.
            shakeCount = 0;
        } else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) {
            shakeCount = shakeCount + 5;
        }else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) {
            if (shakeCount > 0) {
                shakeCount--;
            }
        }
    }
    self.lastAcceleration = acceleration;
}

- (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold {
    double
    deltaX = fabs(last.x - current.x),
    deltaY = fabs(last.y - current.y),
    deltaZ = fabs(last.z - current.z);

    return
    (deltaX > threshold && deltaY > threshold) ||
    (deltaX > threshold && deltaZ > threshold) ||
    (deltaY > threshold && deltaZ > threshold);
}

PS: I've set the update interval to 1/15th of a second.

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)];

Undefined Reference to

g++ test.cpp LinearNode.cpp LinkedList.cpp -o test

Convert INT to DATETIME (SQL)

Try this:

select CONVERT(datetime, convert(varchar(10), 20120103))

How do I trim() a string in angularjs?

JS .trim() is supported in basically everthing, except IE 8 and below.

If you want it to work with that, then, you can use JQuery, but it'll need to be <2.0.0 (as they removed support for IE8 in the 2.x.x line).

Your other option, if you care about IE7/8 (As you mention earlier), is to add trim yourself:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

How to disable Python warnings?

warnings are output via stderr and the simple solution is to append '2> /dev/null' to the CLI. this makes a lot of sense to many users such as those with centos 6 that are stuck with python 2.6 dependencies (like yum) and various modules are being pushed to the edge of extinction in their coverage.

this is especially true for cryptography involving SNI et cetera. one can update 2.6 for HTTPS handling using the proc at: https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl-py2

the warning is still in place, but everything you want is back-ported. the re-direct of stderr will leave you with clean terminal/shell output although the stdout content itself does not change.

responding to FriendFX. sentence one (1) responds directly to the problem with an universal solution. sentence two (2) takes into account the cited anchor re 'disable warnings' which is python 2.6 specific and notes that RHEL/centos 6 users cannot directly do without 2.6. although no specific warnings were cited, para two (2) answers the 2.6 question I most frequently get re the short-comings in the cryptography module and how one can "modernize" (i.e., upgrade, backport, fix) python's HTTPS/TLS performance. para three (3) merely explains the outcome of using the re-direct and upgrading the module/dependencies.

HTML form with two submit buttons and two "target" attributes

I do this on the server-side. That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.

If you have multiple buttons, such as

<form action="mypage" method="get">

  <input type="submit" name="retry" value="Retry" />
  <input type="submit" name="abort" value="Abort" />

</form>

Note : I used GET, but it works for POST too

Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.

This method needs no Javascript.

Note : that some browsers are capable of submitting a form without pressing any buttons (by pressing enter). Non-standard as this is, you have to account for it, by having a clear default action and activating that whenever no buttons were pressed. In other words, make sure your form does something sensible (whether that's displaying a helpful error message or assuming a default) when someone hits enter in a different form element instead of clicking a submit button, rather than just breaking.

Looping over elements in jQuery

Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...

$("#formID").serialize()

It creates a string for you with all of the values automatically.

As for looping through objects, you can also do this.

$.each($("input, select, textarea"), function(i,v) {
    var theTag = v.tagName;
    var theElement = $(v);
    var theValue = theElement.val();
});

Null pointer Exception on .setOnClickListener

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Because Submit button is inside login_modal so you need to use loginDialog view to access button:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

How to detect if multiple keys are pressed at once using JavaScript?

    $(document).ready(function () {
        // using ascii 17 for ctrl, 18 for alt and 83 for "S"
        // ctr+alt+S
        var map = { 17: false, 18: false, 83: false };
        $(document).keyup(function (e) {
            if (e.keyCode in map) {
                map[e.keyCode] = true;
                if (map[17] && map[18] && map[83]) {
                    // Write your own code here, what  you want to do
                    map[17] = false;
                    map[18] = false;
                    map[83] = false;
                }
            }
            else {
                // if u press any other key apart from that "map" will reset.
                map[17] = false;
                map[18] = false;
                map[83] = false;
            }
        });

    });

JQuery Number Formatting

Putting this http://www.mredkj.com/javascript/numberFormat.html and $('.number').formatNumber(); concept together, you may use the following line of code;

e.g. <td class="number">1172907.50</td> will be formatted like <td class="number">1,172,907.50</td>

$('.number').text(function () { 
    var str = $(this).html() + ''; 
    x = str.split('.'); 
    x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; 
    var rgx = /(\d+)(\d{3})/; 
    while (rgx.test(x1)) { 
        x1 = x1.replace(rgx, '$1' + ',' + '$2'); 
    } 
    $(this).html(x1 + x2); 
});

Communication between tabs or windows

This is a development storage part of Tomas M answer for Chrome. We must add listener

window.addEventListener("storage", (e)=> { console.log(e) } );

Load/save item in storage not runt this event - we MUST trigger it manually by

window.dispatchEvent( new Event('storage') ); // THIS IS IMPORTANT ON CHROME

and now, all open tab-s will receive event

C# Collection was modified; enumeration operation may not execute

The error tells you EXACTLY what the problem is (and running in the debugger or reading the stack trace will tell you exactly where the problem is):

C# Collection was modified; enumeration operation may not execute.

Your problem is the loop

foreach (KeyValuePair<int, int> kvp in rankings) {
    //
}

wherein you modify the collection rankings. In particular, the offensive line is

rankings[kvp.Key] = rankings[kvp.Key] + 4;

Before you enter the loop, add the following line:

var listOfRankingsToModify = new List<int>();

Replace the offending line with

listOfRankingsToModify.Add(kvp.Key);

and after you exit the loop

foreach(var key in listOfRankingsToModify) {
    rankings[key] = rankings[key] + 4;
}

That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.

Is it possible to use std::string in a constexpr?

C++20 will add constexpr strings and vectors

The following proposal has been accepted apparently: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0980r0.pdf and it adds constructors such as:

// 20.3.2.2, construct/copy/destroy
constexpr
basic_string() noexcept(noexcept(Allocator())) : basic_string(Allocator()) { }
constexpr
explicit basic_string(const Allocator& a) noexcept;
constexpr
basic_string(const basic_string& str);
constexpr
basic_string(basic_string&& str) noexcept;

in addition to constexpr versions of all / most methods.

There is no support as of GCC 9.1.0, the following fails to compile:

#include <string>

int main() {
    constexpr std::string s("abc");
}

with:

g++-9 -std=c++2a main.cpp

with error:

error: the type ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’} of ‘constexpr’ variable ‘s’ is not literal

std::vector discussed at: Cannot create constexpr std::vector

Tested in Ubuntu 19.04.

OS detecting makefile

I was recently experimenting in order to answer this question I was asking myself. Here are my conclusions:

Since in Windows, you can't be sure that the uname command is available, you can use gcc -dumpmachine. This will display the compiler target.

There may be also a problem when using uname if you want to do some cross-compilation.

Here's a example list of possible output of gcc -dumpmachine:

  • mingw32
  • i686-pc-cygwin
  • x86_64-redhat-linux

You can check the result in the makefile like this:

SYS := $(shell gcc -dumpmachine)
ifneq (, $(findstring linux, $(SYS)))
 # Do Linux things
else ifneq(, $(findstring mingw, $(SYS)))
 # Do MinGW things
else ifneq(, $(findstring cygwin, $(SYS)))
 # Do Cygwin things
else
 # Do things for others
endif

It worked well for me, but I'm not sure it's a reliable way of getting the system type. At least it's reliable about MinGW and that's all I need since it does not require to have the uname command or MSYS package in Windows.

To sum up, uname gives you the system on which you're compiling, and gcc -dumpmachine gives you the system for which you are compiling.

How to adjust the size of y axis labels only in R?

As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use par(cex.lab=2) as a simple alternative. Here's a more advanced mtext() example:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
     yaxt="n", ylab="", 
     xlab="Regular boring x", 
     pch=16,
     col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)

enter image description here

You may need to adjust the line= option to get the optimal positioning of the text but apart from that it's really easy to use.

Convert NSDate to NSString

Define your own utility for format your date required date format for eg.

NSString * stringFromDate(NSDate *date)  
 {   NSDateFormatter *formatter
    [[NSDateFormatter alloc] init];  
    [formatter setDateFormat:@"MM / dd / yyyy, hh?mm a"];    
    return [formatter stringFromDate:date]; 
}

jQuery delete all table rows except first

This should work:

$(document).ready(function() {
   $("someTableSelector").find("tr:gt(0)").remove();
});

Short rot13 function - Python

A one-liner to rot13 a string S:

S.translate({a : a + (lambda x: 1 if x>=0 else -1)(77 - a) * 13 for a in range(65, 91)})

Posting form to different MVC post action depending on the clicked submit button

you can use ajax calls to call different methods without a postback

$.ajax({
    type: "POST",
     url: "@(Url.Action("Action", "Controller"))",
     data: {id: 'id', id1: 'id1' },
     contentType: "application/json; charset=utf-8",
     cache: false,
     async: true,
     success: function (result) {
        //do something
     }
});

python numpy machine epsilon

Another easy way to get epsilon is:

In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16

Table overflowing outside of div

I tried all the solutions mentioned above, then did not work. I have 3 tables one below the other. The last one over flowed. I fixed it using:

/* Grid Definition */
table {
    word-break: break-word;
}

For IE11 in edge mode, you need to set this to word-break:break-all

Telnet is not recognized as internal or external command

You can also try dism /online /Enable-Feature /FeatureName:TelnetClient

Run this command with "Run as an administrator"

Reference

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

The git diff command typically expects one or more commit hashes to generate your diff. You seem to be supplying the name of a remote.

If you had a branch named origin, the commit hash at tip of the branch would have been used if you supplied origin to the diff command, but currently (with no corresponding branch) the command will produce the error you're seeing. It may be the case that you were previously working with a branch named origin.

An alternative, if you're trying to view the difference between your local branch, and a branch on a remote would be something along the lines of:

git diff origin/<branchname>

git diff <branchname> origin/<branchname>

Or other documented variants.

Edit: Having read further, I realise I'm slightly wrong, git diff origin is shorthand for diffing against the head of the specified remote, so git diff origin = git diff origin/HEAD (compare local git branch with remote branch?, Why is "origin/HEAD" shown when running "git branch -r"?)

It sounds like your origin does not have a HEAD, in my case this is because my remote is a bare repository that has never had a HEAD set.

Running git branch -r will show you if origin/HEAD is set, and if so, which branch it points at (e.g. origin/HEAD -> origin/<branchname>).

Shortcut key for commenting out lines of Python code in Spyder

Yes, there is a shortcut for commenting out lines in Python 3.6 (Spyder).

For Single Line Comment, you can use Ctrl+1. It will look like this #This is a sample piece of code

For multi-line comments, you can use Ctrl+4. It will look like this

#============= \#your piece of code \#some more code \#=============

Note : \ represents that the code is carried to another line.

Postgresql - unable to drop database because of some auto connections to DB

In my opinion there are some idle queries running in the backgroud.

  1. Try showing running queries first
SELECT pid, age(clock_timestamp(), query_start), usename, query 
FROM pg_stat_activity 
WHERE query != '<IDLE>' AND query NOT ILIKE '%pg_stat_activity%' 
ORDER BY query_start desc;
  1. kill idle query ( Check if they are referencing the database in question or you can kill all of them or kill a specific using the pid from the select results )

SELECT pg_terminate_backend(procpid);

Note: Killing a select query doesnt make any bad impact

What does "make oldconfig" do exactly in the Linux kernel makefile?

It's torture. Instead of including a generic conf file, they make you hit return 9000 times to generate one.

How to write to a file, using the logging Python module?

I prefer to use a configuration file. It allows me to switch logging levels, locations, etc without changing code when I go from development to release. I simply package a different config file with the same name, and with the same defined loggers.

import logging.config
if __name__ == '__main__':
    # Configure the logger
    # loggerConfigFileName: The name and path of your configuration file
    logging.config.fileConfig(path.normpath(loggerConfigFileName))

    # Create the logger
    # Admin_Client: The name of a logger defined in the config file
    mylogger = logging.getLogger('Admin_Client')

    msg='Bite Me'
    myLogger.debug(msg)
    myLogger.info(msg)
    myLogger.warn(msg)
    myLogger.error(msg)
    myLogger.critical(msg)

    # Shut down the logger
    logging.shutdown()

Here is my code for the log config file

#These are the loggers that are available from the code
#Each logger requires a handler, but can have more than one
[loggers]
keys=root,Admin_Client


#Each handler requires a single formatter
[handlers]
keys=fileHandler, consoleHandler


[formatters]
keys=logFormatter, consoleFormatter


[logger_root]
level=DEBUG
handlers=fileHandler


[logger_Admin_Client]
level=DEBUG
handlers=fileHandler, consoleHandler
qualname=Admin_Client
#propagate=0 Does not pass messages to ancestor loggers(root)
propagate=0


# Do not use a console logger when running scripts from a bat file without a console
# because it hangs!
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=consoleFormatter
args=(sys.stdout,)# The comma is correct, because the parser is looking for args


[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=logFormatter
# This causes a new file to be created for each script
# Change time.strftime("%Y%m%d%H%M%S") to time.strftime("%Y%m%d")
# And only one log per day will be created. All messages will be amended to it.
args=("D:\\Logs\\PyLogs\\" + time.strftime("%Y%m%d%H%M%S")+'.log', 'a')


[formatter_logFormatter]
#name is the name of the logger root or Admin_Client
#levelname is the log message level debug, warn, ect 
#lineno is the line number from where the call to log is made
#04d is simple formatting to ensure there are four numeric places with leading zeros
#4s would work as well, but would simply pad the string with leading spaces, right justify
#-4s would work as well, but would simply pad the string with trailing spaces, left justify
#filename is the file name from where the call to log is made
#funcName is the method name from where the call to log is made
#format=%(asctime)s | %(lineno)d | %(message)s
#format=%(asctime)s | %(name)s | %(levelname)s | %(message)s
#format=%(asctime)s | %(name)s | %(module)s-%(lineno) | %(levelname)s | %(message)s
#format=%(asctime)s | %(name)s | %(module)s-%(lineno)04d | %(levelname)s | %(message)s
#format=%(asctime)s | %(name)s | %(module)s-%(lineno)4s | %(levelname)-8s | %(message)s

format=%(asctime)s | %(levelname)-8s | %(lineno)04d | %(message)s


#Use a separate formatter for the console if you want
[formatter_consoleFormatter]
format=%(asctime)s | %(levelname)-8s | %(filename)s-%(funcName)s-%(lineno)04d | %(message)s

Set Background cell color in PHPExcel

This always running!

$sheet->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setRGB('FF0000');

How to get correct timestamp in C#

var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

Using the slash character in Git branch name

It is possible to have hierarchical branch names (branch names with slash). For example in my repository I have such branch(es). One caveat is that you can't have both branch 'foo' and branch 'foo/bar' in repository.

Your problem is not with creating branch with slash in name.

$ git branch foo/bar
error: unable to resolve reference refs/heads/labs/feature: Not a directory
fatal: Failed to lock ref for update: Not a directory

The above error message talks about 'labs/feature' branch, not 'foo/bar' (unless it is a mistake in copy'n'paste, i.e you edited parts of session). What is the result of git branch or git rev-parse --symbolic-full-name HEAD?

How to bind RadioButtons to an enum?

Based on the EnumToBooleanConverter from Scott. I noticed that the ConvertBack method doesn't work on the Enum with flags code.

I've tried the following code:

public class EnumHasFlagToBooleanConverter : IValueConverter
    {
        private object _obj;
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            _obj = value;
            return ((Enum)value).HasFlag((Enum)parameter);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value.Equals(true))
            {
                if (((Enum)_obj).HasFlag((Enum)parameter))
                {
                    // Do nothing
                    return Binding.DoNothing;
                }
                else
                {
                    int i = (int)_obj;
                    int ii = (int)parameter;
                    int newInt = i+ii;
                    return (NavigationProjectDates)newInt;
                }
            }
            else
            {
                if (((Enum)_obj).HasFlag((Enum)parameter))
                {
                    int i = (int)_obj;
                    int ii = (int)parameter;
                    int newInt = i-ii;
                    return (NavigationProjectDates)newInt;

                }
                else
                {
                    // do nothing
                    return Binding.DoNothing;
                }
            }
        }
    }

The only thing that I can't get to work is to do a cast from int to targetType so I made it hardcoded to NavigationProjectDates, the enum that I use. And, targetType == NavigationProjectDates...


Edit for more generic Flags Enum converter:

    public class FlagsEnumToBooleanConverter : IValueConverter {
        private int _flags=0;
        public object Convert(object value, Type targetType, object parameter, string language) {
            if (value == null) return false;
            _flags = (int) value;
            Type t = value.GetType();
            object o = Enum.ToObject(t, parameter);
            return ((Enum)value).HasFlag((Enum)o);
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            if (value?.Equals(true) ?? false) {
                _flags = _flags | (int) parameter;
            }
            else {
                _flags = _flags & ~(int) parameter;
            }
            return _flags;
        }
    }

Is Java "pass-by-reference" or "pass-by-value"?

I have created a thread devoted to these kind of questions for any programming languages here.

Java is also mentioned. Here is the short summary:

  • Java passes it parameters by value
  • "by value" is the only way in java to pass a parameter to a method
  • using methods from the object given as parameter will alter the object as the references point to the original objects. (if that method itself alters some values)

Differences between JDK and Java SDK

I think jdk has certain features which can be used along with particular framework. Well call it SDK as a whole.

Like Android or Blackberry both use java along with their framework.

How can I reset or revert a file to a specific revision?

git checkout -- foo

That will reset foo to HEAD. You can also:

git checkout HEAD^ foo

for one revision back, etc.

What version of MongoDB is installed on Ubuntu

When you entered in mongo shell using "mongo" command , that time only you will notice

MongoDB shell version v3.4.0-rc2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0-rc2

also you can try command,in mongo shell , db.version()

How to have an automatic timestamp in SQLite?

To complement answers above...

If you are using EF, adorn the property with Data Annotation [Timestamp], then go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:

modelBuilder.Entity<YourEntity>()
                .Property(b => b.Timestamp)
                .ValueGeneratedOnAddOrUpdate()
                .IsConcurrencyToken()
                .ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");

It will make a default value to every data that will be insert into this table.

How can I delete multiple lines in vi?

You can delete multiple(range) lines if you know the line numbers:

:[start_line_no],[end_line_no]d

Note: d stands for delete

where,
start_line_no is the beginning line no you want to delete and end_line_no is the ending line no you want to delete. The lines between the start and end, including start and end will be deleted.

Eg:

:45,101d

The lines between 45 and 101 including 45 and 101 will be deleted.

Include php files when they are in different folders

Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.

How can I make all images of different height and width the same via CSS?

I was looking for a solution for this same problem, to create a list of logos.

I came up with this solution that uses a bit of flexbox, which works for us since we're not worried about old browsers.

This example assumes a 100x100px box but I'm pretty sure the size could be flexible/responsive.

.img__container {
    display: flex;
    padding: 15px 12px;
    box-sizing: border-box;
    width: 100px; height: 100px;

    img {
        margin: auto;
        max-width: 100%;
        max-height: 100%;
    }
}

ps.: you may need to add some prefixes or use autoprefixer.

Format specifier %02x

%02x means print at least 2 digits, prepend it with 0's if there's less. In your case it's 7 digits, so you get no extra 0 in front.

Also, %x is for int, but you have a long. Try %08lx instead.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

if you are using XDocument.Load(url); to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException

See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."

How to Access Hive via Python?

By using Python Client Driver

pip install pyhs2

Then

import pyhs2

with pyhs2.connect(host='localhost',
               port=10000,
               authMechanism="PLAIN",
               user='root',
               password='test',
               database='default') as conn:
with conn.cursor() as cur:
    #Show databases
    print cur.getDatabases()

    #Execute query
    cur.execute("select * from table")

    #Return column info from query
    print cur.getSchema()

    #Fetch table results
    for i in cur.fetch():
        print i

Refer : https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2#SettingUpHiveServer2-PythonClientDriver

Xcode - ld: library not found for -lPods

i have same issue with react-native library called linear-gradient, but i think the problem caused by adding blank space between -L -L... here the screen of error enter image description here

im trying all solution in this page, thank you for help

Select the values of one property on all objects of an array in PowerShell

To complement the preexisting, helpful answers with guidance of when to use which approach and a performance comparison.

  • Outside of a pipeline[1], use (PSv3+):

    $objects.Name
    as demonstrated in rageandqq's answer, which is both syntactically simpler and much faster.

    • Accessing a property at the collection level to get its members' values as an array is called member enumeration and is a PSv3+ feature.

    • Alternatively, in PSv2, use the foreach statement, whose output you can also assign directly to a variable:

      $results = foreach ($obj in $objects) { $obj.Name }

    • If collecting all output from a (pipeline) command in memory first is feasible, you can also combine pipelines with member enumeration; e.g.:

       (Get-ChildItem -File | Where-Object Length -lt 1gb).Name
      
    • Tradeoffs:

      • Both the input collection and output array must fit into memory as a whole.
      • If the input collection is itself the result of a command (pipeline) (e.g., (Get-ChildItem).Name), that command must first run to completion before the resulting array's elements can be accessed.
  • In a pipeline, in case you must pass the results to another command, notably if the original input doesn't fit into memory as a whole, use:

    $objects | Select-Object -ExpandProperty Name

    • The need for -ExpandProperty is explained in Scott Saad's answer (you need it to get only the property value).
    • You get the usual pipeline benefits of the pipeline's streaming behavior, i.e. one-by-one object processing, which typically produces output right away and keeps memory use constant (unless you ultimately collect the results in memory anyway).
    • Tradeoff:
      • Use of the pipeline is comparatively slow.

For small input collections (arrays), you probably won't notice the difference, and, especially on the command line, sometimes being able to type the command easily is more important.


Here is an easy-to-type alternative, which, however is the slowest approach; it uses simplified ForEach-Object syntax called an operation statement (again, PSv3+): ; e.g., the following PSv3+ solution is easy to append to an existing command:

$objects | % Name      # short for: $objects | ForEach-Object -Process { $_.Name }

The PSv4+ .ForEach() array method, more comprehensively discussed in this article, is yet another, well-performing alternative, but note that it requires collecting all input in memory first, just like member enumeration:

# By property name (string):
$objects.ForEach('Name')

# By script block (more flexibility; like ForEach-Object)
$objects.ForEach({ $_.Name })
  • This approach is similar to member enumeration, with the same tradeoffs, except that pipeline logic is not applied; it is marginally slower than member enumeration, though still noticeably faster than the pipeline.

  • For extracting a single property value by name (string argument), this solution is on par with member enumeration (though the latter is syntactically simpler).

  • The script-block variant ({ ... }) allows arbitrary transformations; it is a faster - all-in-memory-at-once - alternative to the pipeline-based ForEach-Object cmdlet (%).

Note: The .ForEach() array method, like its .Where() sibling (the in-memory equivalent of Where-Object), always returns a collection (an instance of [System.Collections.ObjectModel.Collection[psobject]]), even if only one output object is produced.
By contrast, member enumeration, Select-Object, ForEach-Object and Where-Object return a single output object as-is, without wrapping it in a collection (array).


Comparing the performance of the various approaches

Here are sample timings for the various approaches, based on an input collection of 10,000 objects, averaged across 10 runs; the absolute numbers aren't important and vary based on many factors, but it should give you a sense of relative performance (the timings come from a single-core Windows 10 VM:

Important

  • The relative performance varies based on whether the input objects are instances of regular .NET Types (e.g., as output by Get-ChildItem) or [pscustomobject] instances (e.g., as output by Convert-FromCsv).
    The reason is that [pscustomobject] properties are dynamically managed by PowerShell, and it can access them more quickly than the regular properties of a (statically defined) regular .NET type. Both scenarios are covered below.

  • The tests use already-in-memory-in-full collections as input, so as to focus on the pure property extraction performance. With a streaming cmdlet / function call as the input, performance differences will generally be much less pronounced, as the time spent inside that call may account for the majority of the time spent.

  • For brevity, alias % is used for the ForEach-Object cmdlet.

General conclusions, applicable to both regular .NET type and [pscustomobject] input:

  • The member-enumeration ($collection.Name) and foreach ($obj in $collection) solutions are by far the fastest, by a factor of 10 or more faster than the fastest pipeline-based solution.

  • Surprisingly, % Name performs much worse than % { $_.Name } - see this GitHub issue.

  • PowerShell Core consistently outperforms Windows Powershell here.

Timings with regular .NET types:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.005
1.06   foreach($o in $objects) { $o.Name }           0.005
6.25   $objects.ForEach('Name')                      0.028
10.22  $objects.ForEach({ $_.Name })                 0.046
17.52  $objects | % { $_.Name }                      0.079
30.97  $objects | Select-Object -ExpandProperty Name 0.140
32.76  $objects | % Name                             0.148
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.012
1.32   foreach($o in $objects) { $o.Name }           0.015
9.07   $objects.ForEach({ $_.Name })                 0.105
10.30  $objects.ForEach('Name')                      0.119
12.70  $objects | % { $_.Name }                      0.147
27.04  $objects | % Name                             0.312
29.70  $objects | Select-Object -ExpandProperty Name 0.343

Conclusions:

  • In PowerShell Core, .ForEach('Name') clearly outperforms .ForEach({ $_.Name }). In Windows PowerShell, curiously, the latter is faster, albeit only marginally so.

Timings with [pscustomobject] instances:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.006
1.11   foreach($o in $objects) { $o.Name }           0.007
1.52   $objects.ForEach('Name')                      0.009
6.11   $objects.ForEach({ $_.Name })                 0.038
9.47   $objects | Select-Object -ExpandProperty Name 0.058
10.29  $objects | % { $_.Name }                      0.063
29.77  $objects | % Name                             0.184
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.008
1.14   foreach($o in $objects) { $o.Name }           0.009
1.76   $objects.ForEach('Name')                      0.015
10.36  $objects | Select-Object -ExpandProperty Name 0.085
11.18  $objects.ForEach({ $_.Name })                 0.092
16.79  $objects | % { $_.Name }                      0.138
61.14  $objects | % Name                             0.503

Conclusions:

  • Note how with [pscustomobject] input .ForEach('Name') by far outperforms the script-block based variant, .ForEach({ $_.Name }).

  • Similarly, [pscustomobject] input makes the pipeline-based Select-Object -ExpandProperty Name faster, in Windows PowerShell virtually on par with .ForEach({ $_.Name }), but in PowerShell Core still about 50% slower.

  • In short: With the odd exception of % Name, with [pscustomobject] the string-based methods of referencing the properties outperform the scriptblock-based ones.


Source code for the tests:

Note:

  • Download function Time-Command from this Gist to run these tests.

    • Assuming you have looked at the linked code to ensure that it is safe (which I can personally assure you of, but you should always check), you can install it directly as follows:

      irm https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1 | iex
      
  • Set $useCustomObjectInput to $true to measure with [pscustomobject] instances instead.

$count = 1e4 # max. input object count == 10,000
$runs  = 10  # number of runs to average 

# Note: Using [pscustomobject] instances rather than instances of 
#       regular .NET types changes the performance characteristics.
# Set this to $true to test with [pscustomobject] instances below.
$useCustomObjectInput = $false

# Create sample input objects.
if ($useCustomObjectInput) {
  # Use [pscustomobject] instances.
  $objects = 1..$count | % { [pscustomobject] @{ Name = "$foobar_$_"; Other1 = 1; Other2 = 2; Other3 = 3; Other4 = 4 } }
} else {
  # Use instances of a regular .NET type.
  # Note: The actual count of files and folders in your file-system
  #       may be less than $count
  $objects = Get-ChildItem / -Recurse -ErrorAction Ignore | Select-Object -First $count
}

Write-Host "Comparing property-value extraction methods with $($objects.Count) input objects, averaged over $runs runs..."

# An array of script blocks with the various approaches.
$approaches = { $objects | Select-Object -ExpandProperty Name },
              { $objects | % Name },
              { $objects | % { $_.Name } },
              { $objects.ForEach('Name') },
              { $objects.ForEach({ $_.Name }) },
              { $objects.Name },
              { foreach($o in $objects) { $o.Name } }

# Time the approaches and sort them by execution time (fastest first):
Time-Command $approaches -Count $runs | Select Factor, Command, Secs*

[1] Technically, even a command without |, the pipeline operator, uses a pipeline behind the scenes, but for the purpose of this discussion using the pipeline refers only to commands that do use | and therefore involve multiple commands connected by a pipeline.

Dictionary text file

There's also WordNet. Its data files format are well-documented.
I used it for building an embeddable dictionary library for iOS developers (www.lexicontext.com) and also in one of my apps.

Is there an eval() function in Java?

I could advise you to use Exp4j. It is easy to understand as you can see from the following example code:

Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
    .variables("x", "y")
    .build()
    .setVariable("x", 2.3)
    .setVariable("y", 3.14);
double result = e.evaluate();

jQuery SVG vs. Raphael

Oh Raphael has moved on significantly since June. There is a new charting library that can work with it and these are very eye catching. Raphael also supports full SVG path syntax and is incorporating really advanced path methods. Come see 1.2.8+ at my site (Shameless plug) and then bounce over to the Dmitry's site from there. http://www.irunmywebsite.com/raphael/raphaelsource.html

Create, read, and erase cookies with jQuery

As I know, there is no direct support, but you can use plain-ol' javascript for that:

// Cookies
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";               

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

Simple way to understand Encapsulation and Abstraction

Abstraction is a means of hiding details in order to simplify an interface.

So, using a car as an example, all of the controls in a car are abstractions. This allows you to operate a vehicle without understanding the underlying details of the steering, acceleration, or deceleration systems.

A good abstraction is one that standardizes an interface broadly, across multiple instances of a similar problem. A great abstraction can change an industry.

The modern steering wheel, brake pedal, and gas pedal are all examples of great abstractions. Car steering initially looked more like bicycle steering. And both brakes and throttles were operated by hand. But the abstractions we use today were so powerful, they swept the industry.

--

Encapsulation is a means of hiding details in order to protect them from outside manipulation.

Encapsulation is what prevents the driver from manipulating the way the car drives — from the stiffness of the steering, suspension, and braking, to the characteristics of the throttle, and transmission. Most cars do not provide interfaces for changing any of these things. This encapsulation ensures that the vehicle will operate as the manufacturer intended.

Some cars offer a small number of driving modes — like luxury, sport, and economy — which allow the driver to change several of these attributes together at once. By providing driving modes, the manufacturer is allowing the driver some control over the experience while preventing them from selecting a combination of attributes that would render the vehicle less enjoyable or unsafe. In this way, the manufacturer is hiding the details to prevent unsafe manipulations. This is encapsulation.