Programs & Examples On #Unified diff

Hibernate: How to set NULL query-parameter value with HQL?

HQL supports coalesce, allowing for ugly workarounds like:

where coalesce(c.status, 'no-status') = coalesce(:status, 'no-status')

How to create Windows EventLog source from command line?

However the cmd/batch version works you can run into an issue when you want to define an eventID which is higher then 1000. For event creation with an eventID of 1000+ i'll use powershell like this:

$evt=new-object System.Diagnostics.Eventlog(“Define Logbook”)
$evt.Source=”Define Source”
$evtNumber=Define Eventnumber
$evtDescription=”Define description”
$infoevent=[System.Diagnostics.EventLogEntryType]::Define error level
$evt.WriteEntry($evtDescription,$infoevent,$evtNumber) 

Sample:

$evt=new-object System.Diagnostics.Eventlog(“System”)
$evt.Source=”Tcpip”
$evtNumber=4227
$evtDescription=”This is a Test Event”
$infoevent=[System.Diagnostics.EventLogEntryType]::Warning
$evt.WriteEntry($evtDescription,$infoevent,$evtNumber)

How can you run a Java program without main method?

Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.

public class Hello {
  static {
    System.out.println("Hello, World!");
  }
}

Of course, you can run the program as java Hello and you will see the message; however, the command will also fail with a message stating:

Exception in thread "main" java.lang.NoSuchMethodError: main

[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0) immediately after printing the message.

As of JDK6 onward, you no longer see the message from the static initializer block; details here.

Argparse optional positional arguments?

As an extension to @VinaySajip answer. There are additional nargs worth mentioning.

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N (an integer). N arguments from the command line will be gathered together into a list

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

  1. parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

Edit (copied from a comment by @Acumenus) nargs='?' The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.

How to control size of list-style-type disc in CSS?

I have always had good luck with using background images instead of trusting all browsers to interpret the bullet in exactly the same way. This would also give you tight control over the size of the bullet.

.moreLinks li {
    background: url("bullet.gif") no-repeat left 5px;
    padding-left: 1em;
}

Also, you may want to move your DIV outside of the UL. It's invalid markup as you have it now. You can use a list header LH if you must have it inside the list.

CSS I want a div to be on top of everything

For z-index:1000 to have an effect you need a non-static positioning scheme.

Add position:relative; to a rule selecting the element you want to be on top

How do you perform address validation?

You can try Pitney Bowes “IdentifyAddress” Api available at - https://identify.pitneybowes.com/

The service analyses and compares the input addresses against the known address databases around the world to output a standardized detail. It corrects addresses, adds missing postal information and formats it using the format preferred by the applicable postal authority. I also uses additional address databases so it can provide enhanced detail, including address quality, type of address, transliteration (such as from Chinese Kanji to Latin characters) and whether an address is validated to the premise/house number, street, or city level of reference information.

You will find a lot of samples and sdk available on the site and i found it extremely easy to integrate.

How do I grab an INI value within a shell script?

Sed one-liner, that takes sections into account. Example file:

[section1]
param1=123
param2=345
param3=678

[section2]
param1=abc
param2=def
param3=ghi

[section3]
param1=000
param2=111
param3=222

Say you want param2 from section2. Run the following:

sed -nr "/^\[section2\]/ { :l /^param2[ ]*=/ { s/.*=[ ]*//; p; q;}; n; b l;}" ./file.ini

will give you

def

Run local python script on remote server

ssh user@machine python < script.py - arg1 arg2

Because cat | is usually not necessary

Oracle - how to remove white spaces?

SELECT  REGEXP_REPLACE('A B_ __ kunjramansingh smartdude', '\s*', '')
FROM    dual

---
AB___kunjramansinghsmartdude

Update:

Just concatenate strings:

SELECT  a || b
FROM    mytable

What is a PDB file?

A PDB file contains information used by the debugger. It is not required to run your application and it does not need to be included in your released version.

You can disable pdb files from being created in Visual Studio. If you are building from the command line or a script then omit the /Debug switch.

Convert seconds to hh:mm:ss in Python

If you use divmod, you are immune to different flavors of integer division:

# show time strings for 3800 seconds

# easy way to get mm:ss
print "%02d:%02d" % divmod(3800, 60)

# easy way to get hh:mm:ss
print "%02d:%02d:%02d" % \
    reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
        [(3800,),60,60])


# function to convert floating point number of seconds to
# hh:mm:ss.sss
def secondsToStr(t):
    return "%02d:%02d:%02d.%03d" % \
        reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
            [(round(t*1000),),1000,60,60])

print secondsToStr(3800.123)

Prints:

63:20
01:03:20
01:03:20.123

how to show only even or odd rows in sql server 2008?

SELECT *
  FROM   
  ( 
     SELECT rownum rn, empno, ename
     FROM emp
  ) temp
  WHERE  MOD(temp.rn,2) = 1

TypeError: unsupported operand type(s) for -: 'list' and 'list'

This question has been answered but I feel I should also mention another potential cause. This is a direct result of coming across the same error message but for different reasons. If your list/s are empty the operation will not be performed. check your code for indents and typos

Why rgb and not cmy?

This is nothing to do with hardware nor software. Simply that RGB are the 3 primary colours which can be combined in various ways to produce every other colour. It is more about the human convention/perception of colours which carried over.

You may find this article interesting.

String to HtmlDocument

I've adapted Nikhil's answer somewhat to simplify it. Admittedly, I have not run it through a .net compiler and there are likely very good reasons for the lines Nikhil put in which I have omitted. However, at least in my use case (a very simple page) they were unnecessary.

My use case was for a quick powershell script:

$htmlText = $(New-Object 
System.Net.WebClient).DownloadString("<URI HERE>") #Get the HTML document from a webserver
$browser = New-Object System.Windows.Forms.WebBrowser
$browser.DocumentText = $htmlText
$browser.Document.Write($htmlText)
$response = $browser.document

For my case, this returned an HTMLDocument object with HTMLElement objects in it, instead of __ComObject object types (which are a challenge to use in powershell class code) returned by a call to Invoke-WebRequest in PS 5.1.14393.1944

I believe the equivalent C# code is:

public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
{
    WebBrowser browser = new WebBrowser();
    browser.DocumentText = html;
    browser.Document.Write(html);
    return browser.Document;
}

Python convert object to float

I eventually used:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)

It worked just fine, except that I got the following message.

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

split python source code into multiple files?

Sure!

#file  -- test.py --
myvar = 42
def test_func():
    print("Hello!")

Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH) Note that the current directory is always in PYTHONPATH, so if use_test is being run from the same directory where test.py lives, you're all set:

#file -- use_test.py --
import test
test.test_func()  #prints "Hello!"
print (test.myvar)  #prints 42

from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar)     #Exception (NameError)

from test import *
test_func() #prints "Hello"
print(myvar)      #prints 42

There's a lot more you can do than just that through the use of special __init__.py files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.

chart.js load totally new data

It is an old thread, but in the current version (as of 1-feb-2017), it easy to replace datasets plotted on chart.js:

suppose your new x-axis values are in array x and y-axis values are in array y, you can use below code to update the chart.

var x = [1,2,3];
var y = [1,1,1];

chart.data.datasets[0].data = y;
chart.data.labels = x;

chart.update();

Get pixel's RGB using PIL

An alternative to converting the image is to create an RGB index from the palette.

from PIL import Image

def chunk(seq, size, groupByList=True):
    """Returns list of lists/tuples broken up by size input"""
    func = tuple
    if groupByList:
        func = list
    return [func(seq[i:i + size]) for i in range(0, len(seq), size)]


def getPaletteInRgb(img):
    """
    Returns list of RGB tuples found in the image palette
    :type img: Image.Image
    :rtype: list[tuple]
    """
    assert img.mode == 'P', "image should be palette mode"
    pal = img.getpalette()
    colors = chunk(pal, 3, False)
    return colors

# Usage
im = Image.open("image.gif")
pal = getPalletteInRgb(im)

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

Center fixed div with dynamic width (CSS)

<div id="container">
    <div id="some_kind_of_popup">
        center me
    </div>
</div>

You'd need to wrap it in a container. here's the css

#container{
    position: fixed;
    top: 100px;
    width: 100%;
    text-align: center;
}
#some_kind_of_popup{
    display:inline-block;
    width: 90%;
    max-width: 900px;  
    min-height: 300px;  
}

What are invalid characters in XML

OK, let's separate the question of the characters that:

  1. aren't valid at all in any XML document.
  2. need to be escaped.

The answer provided by @dolmen in "What are invalid characters in XML" is still valid but needs to be updated with the XML 1.1 specification.

1. Invalid characters

The characters described here are all the characters that are allowed to be inserted in an XML document.

1.1. In XML 1.0

The global list of allowed characters is:

[2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */

Basically, the control characters and characters out of the Unicode ranges are not allowed. This means also that calling for example the character entity &#x3; is forbidden.

1.2. In XML 1.1

The global list of allowed characters is:

[2] Char ::= [#x1-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */

[2a] RestrictedChar ::= [#x1-#x8] | [#xB-#xC] | [#xE-#x1F] | [#x7F-#x84] | [#x86-#x9F]

This revision of the XML recommendation has extended the allowed characters so control characters are allowed, and takes into account a new revision of the Unicode standard, but these ones are still not allowed : NUL (x00), xFFFE, xFFFF...

However, the use of control characters and undefined Unicode char is discouraged.

It can also be noticed that all parsers do not always take this into account and XML documents with control characters may be rejected.

2. Characters that need to be escaped (to obtain a well-formed document):

The < must be escaped with a &lt; entity, since it is assumed to be the beginning of a tag.

The & must be escaped with a &amp; entity, since it is assumed to be the beginning a entity reference

The > should be escaped with &gt; entity. It is not mandatory -- it depends on the context -- but it is strongly advised to escape it.

The ' should be escaped with a &apos; entity -- mandatory in attributes defined within single quotes but it is strongly advised to always escape it.

The " should be escaped with a &quot; entity -- mandatory in attributes defined within double quotes but it is strongly advised to always escape it.

How to empty ("truncate") a file on linux that already exists and is protected in someway?

Any one can try this command to truncate any file in linux system

This will surely work in any format :

truncate -s 0 file.txt

Saving an image in OpenCV

From my experiences the first few frames that are captured when using:

frame = cvQueryFrame( capture );

Tend to be blank. You may want to wait a short while(about 3 seconds) and then try to capture the image.

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

How to get Selected Text from select2 when using <input>

Also you can have the selected value using following code:

alert("Selected option value is: "+$('#SelectelementId').select2("val"));

Google Map API v3 — set bounds and center

The answers are perfect for adjust map boundaries for markers but if you like to expand Google Maps boundaries for shapes like polygons and circles, you can use following codes:

For Circles

bounds.union(circle.getBounds());

For Polygons

polygon.getPaths().forEach(function(path, index)
{
    var points = path.getArray();
    for(var p in points) bounds.extend(points[p]);
});

For Rectangles

bounds.union(overlay.getBounds());

For Polylines

var path = polyline.getPath();

var slat, blat = path.getAt(0).lat();
var slng, blng = path.getAt(0).lng();

for(var i = 1; i < path.getLength(); i++)
{
    var e = path.getAt(i);
    slat = ((slat < e.lat()) ? slat : e.lat());
    blat = ((blat > e.lat()) ? blat : e.lat());
    slng = ((slng < e.lng()) ? slng : e.lng());
    blng = ((blng > e.lng()) ? blng : e.lng());
}

bounds.extend(new google.maps.LatLng(slat, slng));
bounds.extend(new google.maps.LatLng(blat, blng));

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

I found it hard to decipher what is meant by "working directory of the VM". In my example, I was using the Java Service Wrapper program to execute a jar - the dump files were created in the directory where I had placed the wrapper program, e.g. c:\myapp\bin. The reason I discovered this is because the files can be quite large and they filled up the hard drive before I discovered their location.

C: socket connection timeout

Set the socket non-blocking, and use select() (which takes a timeout parameter). If a non-blocking socket is trying to connect, then select() will indicate that the socket is writeable when the connect() finishes (either successfully or unsuccessfully). You then use getsockopt() to determine the outcome of the connect():

int main(int argc, char **argv) {
    u_short port;                /* user specified port number */
    char *addr;                  /* will be a pointer to the address */
    struct sockaddr_in address;  /* the libc network address data structure */
    short int sock = -1;         /* file descriptor for the network socket */
    fd_set fdset;
    struct timeval tv;

    if (argc != 3) {
        fprintf(stderr, "Usage %s <port_num> <address>\n", argv[0]);
        return EXIT_FAILURE;
    }

    port = atoi(argv[1]);
    addr = argv[2];

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr(addr); /* assign the address */
    address.sin_port = htons(port);            /* translate int2port num */

    sock = socket(AF_INET, SOCK_STREAM, 0);
    fcntl(sock, F_SETFL, O_NONBLOCK);

    connect(sock, (struct sockaddr *)&address, sizeof(address));

    FD_ZERO(&fdset);
    FD_SET(sock, &fdset);
    tv.tv_sec = 10;             /* 10 second timeout */
    tv.tv_usec = 0;

    if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
    {
        int so_error;
        socklen_t len = sizeof so_error;

        getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);

        if (so_error == 0) {
            printf("%s:%d is open\n", addr, port);
        }
    }

    close(sock);
    return 0;
}

Conditionally displaying JSF components

Yes, use the rendered attribute.

<h:form rendered="#{some boolean condition}">

You usually tie it to the model rather than letting the model grab the component and manipulate it.

E.g.

<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

Note the importance of keyword based EL operators such as gt, ge, le and lt instead of >, >=, <= and < as angle brackets < and > are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.

As to your specific use case, let's assume that the link is passing a parameter like below:

<a href="page.xhtml?form=1">link</a>

You can then show the form as below:

<h:form rendered="#{param.form eq '1'}">

(the #{param} is an implicit EL object referring to a Map representing the request parameters)

See also:

Populate XDocument from String

You can use XDocument.Parse(string) instead of Load(string).

async/await - when to return a Task vs void?

I think you can use async void for kicking off background operations as well, so long as you're careful to catch exceptions. Thoughts?

class Program {

    static bool isFinished = false;

    static void Main(string[] args) {

        // Kick off the background operation and don't care about when it completes
        BackgroundWork();

        Console.WriteLine("Press enter when you're ready to stop the background operation.");
        Console.ReadLine();
        isFinished = true;
    }

    // Using async void to kickoff a background operation that nobody wants to be notified about when it completes.
    static async void BackgroundWork() {
        // It's important to catch exceptions so we don't crash the appliation.
        try {
            // This operation will end after ten interations or when the app closes. Whichever happens first.
            for (var count = 1; count <= 10 && !isFinished; count++) {
                await Task.Delay(1000);
                Console.WriteLine($"{count} seconds of work elapsed.");
            }
            Console.WriteLine("Background operation came to an end.");
        } catch (Exception x) {
            Console.WriteLine("Caught exception:");
            Console.WriteLine(x.ToString());
        }
    }
}

Rebasing a Git merge commit

Given that I just lost a day trying to figure this out and actually found a solution with the help of a coworker, I thought I should chime in.

We have a large code base and we have to deal with 2 branch heavily being modified at the same time. There is a main branch and a secondary branch if you which.

While I merge the secondary branch into the main branch, work continues in the main branch and by the time i'm done, I can't push my changes because they are incompatible.

I therefore need to "rebase" my "merge".

This is how we finally did it :

1) make note of the SHA. ex.: c4a924d458ea0629c0d694f1b9e9576a3ecf506b

git log -1

2) Create the proper history but this will break the merge.

git rebase -s ours --preserve-merges origin/master

3) make note of the SHA. ex.: 29dd8101d78

git log -1

4) Now reset to where you were before

git reset c4a924d458ea0629c0d694f1b9e9576a3ecf506b --hard

5) Now merge the current master into your working branch

git merge origin/master
git mergetool
git commit -m"correct files

6) Now that you have the right files, but the wrong history, get the right history on top of your change with :

git reset 29dd8101d78 --soft

7) And then --amend the results in your original merge commit

git commit --amend

Voila!

Python: finding an element in a list

assuming you want to find a value in a numpy array, I guess something like this might work:

Numpy.where(arr=="value")[0]

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

In Python, how do I iterate over a dictionary in sorted key order?

Use the sorted() function:

return sorted(dict.iteritems())

If you want an actual iterator over the sorted results, since sorted() returns a list, use:

return iter(sorted(dict.iteritems()))

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

I have been using both committing the node_modules folder and shrink-wrapping. Both solutions did not make me happy.

In short: a committed node_modules folder adds too much noise to the repository.And shrinkwrap.json is not easy to manage and there isn't any guarantee that some shrink-wrapped project will build in a few years.

I found that Mozilla was using a separate repository for one of their projects: https://github.com/mozilla-b2g/gaia-node-modules

So it did not take me long to implement this idea in a Node.js CLI tool: https://github.com/bestander/npm-git-lock

Just before every build, add:

npm-git-lock --repo [[email protected]:your/dedicated/node_modules/git/repository.git]

It will calculate the hash of your package.json file and will either check out folder node_modules content from a remote repository, or, if it is a first build for this package.json file, will do a clean npm install and push the results to the remote repository.

ssh: connect to host github.com port 22: Connection timed out

Execute:

nc -v -z <git-repository> <port>

Your output should look like:

"Connection to <git-repository> <port> port [tcp/*] succeeded!"

If you get:

connect to <git-repository> <port> (tcp) failed: Connection timed out

You need to edit your ~/.ssh/config file. Add something like the following:

Host example.com
Port 1234

Regular Expression to select everything before and up to a particular text

Up to and including txt you would need to change your regex like so:

^(.*?\\.txt)

The request was aborted: Could not create SSL/TLS secure channel

In my case I had this problem when a Windows service tried to connected to a web service. Looking in Windows events finally I found a error code.

Event ID 36888 (Schannel) is raised:

The following fatal alert was generated: 40. The internal error state is 808.

Finally it was related with a Windows Hotfix. In my case: KB3172605 and KB3177186

The proposed solution in vmware forum was add a registry entry in windows. After adding the following registry all works fine.

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\KeyExchangeAlgorithms\Diffie-Hellman]

"ClientMinKeyBitLength"=dword:00000200

Apparently it's related with a missing value in the https handshake in the client side.

List your Windows HotFix:

wmic qfe list

Solution Thread:

https://communities.vmware.com/message/2604912#2604912

Hope it's helps.

How do you redirect to a page using the POST verb?

If you want to pass data between two actions during a redirect without include any data in the query string, put the model in the TempData object.

ACTION

TempData["datacontainer"] = modelData;

VIEW

var modelData= TempData["datacontainer"] as ModelDataType; 

TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only! Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this.

Therefore, the only scenario where using TempData will reliably work is when you are redirecting.

What is the difference between Document style and RPC style communication?

Document
Document style messages can be validated against predefined schema. In document style, SOAP message is sent as a single document. Example of schema:

  <types>  
   <xsd:schema> <xsd:import namespace="http://example.com/" 
    schemaLocation="http://localhost:8080/ws/hello?xsd=1"/>  
   </xsd:schema>  
  </types>

Example of document style soap body message

  <message name="getHelloWorldAsString">   
     <part name="parameters" element="tns:getHelloWorldAsString"/>   
  </message> 
  <message name="getHelloWorldAsStringResponse">  
     <part name="parameters"> element="tns:getHelloWorldAsStringResponse"/>   
  </message>

Document style message is loosely coupled.

RPC RPC style messages use method name and parameters to generate XML structure. messages are difficult to be validated against schema. In RPC style, SOAP message is sent as many elements.

  <message name="getHelloWorldAsString">
    <part name="arg0"> type="xsd:string"/>   
   </message> 
  <message name="getHelloWorldAsStringResponse">   
    <part name="return"
   > type="xsd:string"/>   
  </message>

Here each parameters are discretely specified, RPC style message is tightly coupled, is typically static, requiring changes to the client when the method signature changes The rpc style is limited to very simple XSD types such as String and Integer, and the resulting WSDL will not even have a types section to define and constrain the parameters

Literal By default style. Data is serialized according to a schema, data type not specified in messages but a reference to schema(namespace) is used to build soap messages.

   <soap:body>
     <myMethod>
        <x>5</x>
        <y>5.0</y>
     </myMethod>
   </soap:body>

Encoded Datatype specified in each parameter

   <soap:body>
     <myMethod>
         <x xsi:type="xsd:int">5</x>
         <y xsi:type="xsd:float">5.0</y>
     </myMethod>
   </soap:body>

Schema free

DELETE ... FROM ... WHERE ... IN

You can achieve this using exists:

DELETE
  FROM table1
 WHERE exists(
           SELECT 1
             FROM table2
            WHERE table2.stn = table1.stn
              and table2.jaar = year(table1.datum)
       )

how to make negative numbers into positive

a *= (-1);

problem solved. If there is a smaller solution for a problem, then why you guys going for a complex solution. Please direct people to use the base logic also because then only the people can train their programming logic.

Making a button invisible by clicking another button in HTML

  1. getElementById returns a single object for which you can specify the style.So, the above explanation is correct.

  2. getElementsByTagName returns multiple objects(array of objects and properties) for which we cannot apply the style directly.

Error inflating class android.support.v7.widget.Toolbar?

In the case of Xamarin in VS, you must add

Theme = "@style/MyThemesss"

to youractivity.cs.

I add this and go on.

Catch browser's "zoom" event in JavaScript

Lets define px_ratio as below:

px ratio = ratio of physical pixel to css px.

if any one zoom The Page, the viewport pxes (px is different from pixel ) reduces and should be fit to The screen so the ratio (physical pixel / CSS_px ) must get bigger.

but in window Resizing, screen size reduces as well as pxes. so the ratio will maintain.

zooming: trigger windows.resize event --> and change px_ratio

but

resizing: trigger windows.resize event --> doesn’t change px_ratio

//for zoom detection
px_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;

$(window).resize(function(){isZooming();});

function isZooming(){
    var newPx_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
    if(newPx_ratio != px_ratio){
        px_ratio = newPx_ratio;
        console.log("zooming");
        return true;
    }else{
        console.log("just resizing");
        return false;
    }
}

The key point is difference between CSS PX and Physical Pixel.

https://gist.github.com/abilogos/66aba96bb0fb27ab3ed4a13245817d1e

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

How to connect to my http://localhost web server from Android Emulator

Another workaround is to get a free domain from no-ip.org and point it to your local ip address. Then, instead of using http://localhost/yourwebservice you can try http://yourdomain.no-ip.org/yourwebservice

How to create a Date in SQL Server given the Day, Month and Year as Integers

CREATE DATE USING MONTH YEAR IN SQL::

DECLARE @FromMonth int=NULL,
@ToMonth int=NULL,
@FromYear int=NULL,
@ToYear int=NULL

/**Region For Create Date**/
        DECLARE @FromDate DATE=NULL
        DECLARE @ToDate DATE=NULL

    SET @FromDate=DateAdd(day,0, DateAdd(month, @FromMonth - 1,DateAdd(Year, @FromYear-1900, 0)))
    SET @ToDate=DateAdd(day,-1, DateAdd(month, @ToMonth - 0,DateAdd(Year, @ToYear-1900, 0)))
/**Region For Create Date**/

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

How can I get a specific parameter from location.search?

The easiest way is to have

if (document.location.search.indexOf('yourtext=') >= 0) {
    // your code
} else {
    // what happens?
}

indexOf()

The indexOf(text) function returns

  • A WHOLE NUMBER BELOW 0 when the text passed in the function is not in whatever variable or string you are looking for - in this case document.location.search.
  • A WHOLE NUMBER EQUAL TO 0 OR HIGHER when the text passed in the function is in whatever variable or string you are looking for - in this case document.location.search.

I hope this was useful, @gumbo

Mockito: List Matchers with generics

Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:

import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;

verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());

Android SDK manager won't open

Try adding the Java path (pointing to the JDK) to the System Environment Variables.

Right-click 'Computer' > Properties > Advanced system settings > Environment Variables

Then under System Variables, add a new variable.

Variable   Value
JAVA_PATH  C:\Program Files\Java\jdk1.7.0

Then edit the Path variable, prefix it with %JAVA_PATH%\bin;.

Wrap text in <td> tag

It's possible that this might work, but it might prove to be a bit of a nuisance at some point in the future (if not immediately).

<style> 
tbody td span {display: inline-block;
               width: 10em; /* this is the nuisance part, as you'll have to define a particular width, and I assume -without testing- that any percent widths would be relative to the containing `<td>`, not the `<tr>` or `<table>` */
               overflow: hidden; 
               white-space: nowrap; }

</style>

...

<table>

<thead>...</thead>
<tfoot>...</tfoot>

<tbody>

<tr>

<td><span title="some text">some text</span></td> <td><span title="some more text">some more text</span></td> <td><span title="yet more text">yet more text</span></td>

</tr>

</tbody>

</table>

The rationale for the span is that, as pointed out by others, a <td> will typically expand to accommodate the content, whereas a <span> can be given -and expected to keep- a set width; the overflow: hidden is intended to, but might not, hide what would otherwise cause the <td> to expand.

I'd recommend using the title property of the span to show the text that's present (or clipped) in the visual cell, so that the text's still available (and if you don't want/need people to see it, then why have it in the first place, I guess...).

Also, if you define a width for the td {...} the td will expand (or potentially contract, but I doubt it) to fill its implied width (as I see it this seems to be table-width/number-of-cells), a specified table-width doesn't seem to create the same issue.

The downside is additional markup used for presentation.

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

I have IntelliJ IDEA 12.x on the Mac and I use Maven 3 and I get the red highlighting over my code even though the Maven build is fine. None of the above (re-indexing, force import, etc.) worked for me. I had to do the following:

Intellij -> Preferences -> Maven -> Importing
    [ ] Use Maven3 to import projects

I have to check the Maven3 import option and that fixes the issue.

Serializing and submitting a form with jQuery and PHP

 $("#contactForm").submit(function() {

    $.post(url, $.param($(this).serializeArray()), function(data) {

    });
 });

How to increase request timeout in IIS?

In IIS Manager, right click on the site and go to Manage Web Site -> Advanced Settings. Under Connection Limits option, you should see Connection Time-out.

Setting a JPA timestamp column to be generated by the database?

@Column(name = "LastTouched", insertable = false, updatable = false, columnDefinition = "TIMESTAMP default getdate()")
@Temporal(TemporalType.TIMESTAMP)
private Date LastTouched;`enter code here`

How to make <div> fill <td> height

CSS height: 100% only works if the element's parent has an explicitly defined height. For example, this would work as expected:

td {
    height: 200px;
}

td div {
    /* div will now take up full 200px of parent's height */
    height: 100%;
}

Since it seems like your <td> is going to be variable height, what if you added the bottom right icon with an absolutely positioned image like so:

.thatSetsABackgroundWithAnIcon {
    /* Makes the <div> a coordinate map for the icon */
    position: relative;

    /* Takes the full height of its parent <td>.  For this to work, the <td>
       must have an explicit height set. */
    height: 100%;
}

.thatSetsABackgroundWithAnIcon .theIcon {        
    position: absolute;
    bottom: 0;
    right: 0;
}

With the table cell markup like so:

<td class="thatSetsABackground">  
  <div class="thatSetsABackgroundWithAnIcon">    
    <dl>
      <dt>yada
      </dt>
      <dd>yada
      </dd>
    </dl>
    <img class="theIcon" src="foo-icon.png" alt="foo!"/>
  </div>
</td>

Edit: using jQuery to set div's height

If you keep the <div> as a child of the <td>, this snippet of jQuery will properly set its height:

// Loop through all the div.thatSetsABackgroundWithAnIcon on your page
$('div.thatSetsABackgroundWithAnIcon').each(function(){
    var $div = $(this);

    // Set the div's height to its parent td's height
    $div.height($div.closest('td').height());
});

Create auto-numbering on images/figures in MS Word

  • Select whole document (Ctrl+A)
  • Press F9
  • Save

Should update the figure caption automatically.

My question is tho, how can one also 'assign' referenced figures '(Fig.4)' in the text to do the same thing - aka change when an image is added above it?

EDIT: Figured it out.. In word go to Insert and Cross-ref and assign the ref. Then Ctrl+A and F9 and everything should sort itself out.

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

How to read AppSettings values from a .json file in ASP.NET Core

Super late to the party but if someone finds this out.

You can call IConfiguration from Microsoft.Extensions.Configuration;

public static IConfiguration Configuration { get; }
public static string MyAwesomeString = Configuration.GetSection("appSettings")["MyAwesomeString"].ToString();

display: inline-block extra margin

Cleaner way to remove those spaces is by using float: left; :

DEMO

HTML:

<div>Some Text</div>
<div>Some Text</div>

CSS:

div {
    background-color: red;
    float: left;
}

I'ts supported in all new browsers. Never got it why back when IE ruled lot's of developers didn't make sue their site works well on firefox/chrome, but today, when IE is down to 14.3 %. anyways, didn't have many issues in IE-9 even thought it's not supported, for example the above demo works fine.

java.net.URL read stream to byte[]

byte[] b = IOUtils.toByteArray((new URL( )).openStream()); //idiom

Note however, that stream is not closed in the above example.

if you want a (76-character) chunk (using commons codec)...

byte[] b = Base64.encodeBase64(IOUtils.toByteArray((new URL( )).openStream()), true);

Line break (like <br>) using only css

It works like this:

h4 {
    display:inline;
}
h4:after {
    content:"\a";
    white-space: pre;
}

Example: http://jsfiddle.net/Bb2d7/

The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)

How to resize the jQuery DatePicker control

The Jacob Tsui solution works perfect for me:

$('#event_date').datepicker({
    showButtonPanel: true,
    dateFormat: "mm/dd/yy",
    beforeShow: function(){ 
        $(".ui-datepicker").css('font-size', 12)
    }
});

How to get sp_executesql result into a variable?

If you want to return more than 1 value use this:

DECLARE @sqlstatement2      NVARCHAR(MAX);
DECLARE @retText            NVARCHAR(MAX);  
DECLARE @ParmDefinition     NVARCHAR(MAX);
DECLARE @retIndex           INT = 0;

SELECT @sqlstatement = 'SELECT @retIndexOUT=column1 @retTextOUT=column2 FROM XXX WHERE bla bla';

SET @ParmDefinition = N'@retIndexOUT INT OUTPUT, @retTextOUT NVARCHAR(MAX) OUTPUT';

exec sp_executesql @sqlstatement, @ParmDefinition, @retIndexOUT=@retIndex OUTPUT, @retTextOUT=@retText OUTPUT;

returned values are in @retIndex and @retText

What data type to use for money in Java?

I like using Tiny Types which would wrap either a double, BigDecimal, or int as previous answers have suggested. (I would use a double unless precision problems crop up).

A Tiny Type gives you type safety so you don't confused a double money with other doubles.

Is there a Social Security Number reserved for testing/examples?

There are multiple number groups and some particular numbers that will never be allocated:

Consider using one of these (the obviously invalid 000-00-0000 would be a good one IMO).

(Answer has been updated to provide source information beyond Wikipedia and remove information that is no longer accurate after the SSA made its randomization change in mid 2011.)

How to connect to a secure website using SSL in Java with a pkcs12 file?

The following steps will help you to sort your problem out.

Steps: developer_identity.cer <= download from Apple mykey.p12 <= Your private key

Commands to follow:

    openssl x509 -in developer_identity.cer -inform DER -out developer_identity.pem -outform PEM

    openssl pkcs12 -nocerts -in mykey.p12 -out mykey.pem

    openssl pkcs12 -export -inkey mykey.pem -in developer_identity.pem -out iphone_dev.p12

Final p12 that we will require is iphone_dev.p12 file and the passphrase.

use this file as your p12 and then try. This indeed is the solution.:)

How can I use MS Visual Studio for Android Development?

You can use Visual Studio 2015 to building cross-platform apps for Android, iOS, and Windows.

IDE: https://www.visualstudio.com/en-US/explore/cordova-vs

Hope this will help!

How to apply !important using .css()?

There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.

Just overwrite style, but you don't have to parse anything, why would you?

// Accepts the hyphenated versions (i.e. not 'cssFloat')
function addStyle(element, property, value, important) {
    // Remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    // Insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

Can't use removeProperty(), because it won't remove !important rules in Chrome.
Can't use element.style[property] = '', because it only accepts camelCase in Firefox.

You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, Internet Explorer 8, etc.

Best way to save a trained model in PyTorch?

The pickle Python library implements binary protocols for serializing and de-serializing a Python object.

When you import torch (or when you use PyTorch) it will import pickle for you and you don't need to call pickle.dump() and pickle.load() directly, which are the methods to save and to load the object.

In fact, torch.save() and torch.load() will wrap pickle.dump() and pickle.load() for you.

A state_dict the other answer mentioned deserves just few more notes.

What state_dict do we have inside PyTorch? There are actually two state_dicts.

The PyTorch model is torch.nn.Module has model.parameters() call to get learnable parameters (w and b). These learnable parameters, once randomly set, will update over time as we learn. Learnable parameters are the first state_dict.

The second state_dict is the optimizer state dict. You recall that the optimizer is used to improve our learnable parameters. But the optimizer state_dict is fixed. Nothing to learn in there.

Because state_dict objects are Python dictionaries, they can be easily saved, updated, altered, and restored, adding a great deal of modularity to PyTorch models and optimizers.

Let's create a super simple model to explain this:

import torch
import torch.optim as optim

model = torch.nn.Linear(5, 2)

# Initialize optimizer
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)

print("Model's state_dict:")
for param_tensor in model.state_dict():
    print(param_tensor, "\t", model.state_dict()[param_tensor].size())

print("Model weight:")    
print(model.weight)

print("Model bias:")    
print(model.bias)

print("---")
print("Optimizer's state_dict:")
for var_name in optimizer.state_dict():
    print(var_name, "\t", optimizer.state_dict()[var_name])

This code will output the following:

Model's state_dict:
weight   torch.Size([2, 5])
bias     torch.Size([2])
Model weight:
Parameter containing:
tensor([[ 0.1328,  0.1360,  0.1553, -0.1838, -0.0316],
        [ 0.0479,  0.1760,  0.1712,  0.2244,  0.1408]], requires_grad=True)
Model bias:
Parameter containing:
tensor([ 0.4112, -0.0733], requires_grad=True)
---
Optimizer's state_dict:
state    {}
param_groups     [{'lr': 0.001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'params': [140695321443856, 140695321443928]}]

Note this is a minimal model. You may try to add stack of sequential

model = torch.nn.Sequential(
          torch.nn.Linear(D_in, H),
          torch.nn.Conv2d(A, B, C)
          torch.nn.Linear(H, D_out),
        )

Note that only layers with learnable parameters (convolutional layers, linear layers, etc.) and registered buffers (batchnorm layers) have entries in the model's state_dict.

Non learnable things, belong to the optimizer object state_dict, which contains information about the optimizer's state, as well as the hyperparameters used.

The rest of the story is the same; in the inference phase (this is a phase when we use the model after training) for predicting; we do predict based on the parameters we learned. So for the inference, we just need to save the parameters model.state_dict().

torch.save(model.state_dict(), filepath)

And to use later model.load_state_dict(torch.load(filepath)) model.eval()

Note: Don't forget the last line model.eval() this is crucial after loading the model.

Also don't try to save torch.save(model.parameters(), filepath). The model.parameters() is just the generator object.

On the other side, torch.save(model, filepath) saves the model object itself, but keep in mind the model doesn't have the optimizer's state_dict. Check the other excellent answer by @Jadiel de Armas to save the optimizer's state dict.

Change Background color (css property) using Jquery

Try this

$("body").css({"background-color":"blue"}); 

jquery dialog save cancel button styling

I had to use the following construct in jQuery UI 1.8.22:

var buttons = $('.ui-dialog-buttonset').children('button');
buttons.removeClass().addClass('button');

This removes all formatting and applies the replacement styling as needed.
Works in most major browsers.

How do I import/include MATLAB functions?

Solution for Windows

Go to File --> Set Path and add the folder containing the functions as Matlab files. (At least for Matlab 2007b on Vista)

Control the dashed border stroke length and distance between strokes

Css render is browser specific and I don't know any fine tuning on it, you should work with images as recommended by Ham. Reference: http://www.w3.org/TR/CSS2/box.html#border-style-properties

Wordpress - Images not showing up in the Media Library

Well, Seems like there was a bug when creating custom post types in the function.php file of the theme... which bugged that.

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

Bind failed: Address already in use

It also happens when you have not give enough permissions(read and write) to your sock file!

Just add expected permission to your sock contained folder and your sock file:

 chmod ug+rw /path/to/your/
 chmod ug+rw /path/to/your/file.sock

Then have fun!

Find what 2 numbers add to something and multiply to something

Come on guys, there is no need to loop, just use simple math to solve this equation system:

a*b = i;

a+b = j;

a = j/b;

a = i-b;

j/b = i-b; so:

b + j/b + i = 0

b^2 + i*b + j = 0

From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.

EDIT:

There you go:

function finder($add,$product)
{

 $inside_root = $add*$add - 4*$product;

 if($inside_root >=0)
 {

     $b = ($add + sqrt($inside_root))/2;
     $a = $add - $b;

     echo "$a+$b = $add and $a*$b=$product\n";

 }else
 {
   echo "No real solution\n";
 }
}

Real live action:

http://codepad.org/JBxMgHBd

Get a DataTable Columns DataType

dt.Columns[0].DataType.Name.ToString()

Why can't I reference my class library?

You may forget to add reference the class library which you needed to import.

Right click the class library which you want to import in (which contains multiple imported class libraries), -->Add->Reference(Select Projects->Solution->select the class library which you want to import from->OK)

jQuery Scroll to Div

if the link element is:

<a id="misc" href="#misc">Miscellaneous</a>

and the Miscellaneous category is bounded by something like:

<p id="miscCategory" name="misc">....</p>

you can use jQuery to do the desired effect:

<script type="text/javascript">
  $("#misc").click(function() {
    $("#miscCategory").animate({scrollTop: $("#miscCategory").offset().top});
  });
</script>

as far as I remember it correctly.. (though, I haven't tested it and wrote it from memory)

How to send a simple string between two programs using pipes?

This answer might be helpful for a future Googler.

#include <stdio.h>
#include <unistd.h>

int main(){     
     int p, f;  
     int rw_setup[2];   
     char message[20];      
     p = pipe(rw_setup);    
     if(p < 0){         
        printf("An error occured. Could not create the pipe.");  
        _exit(1);   
     }      
     f = fork();    
     if(f > 0){
        write(rw_setup[1], "Hi from Parent", 15);    
     }  
     else if(f == 0){       
        read(rw_setup[0],message,15);       
        printf("%s %d\n", message, r_return);   
     }  
     else{      
        printf("Could not create the child process");   
     }      
     return 0;

}

You can find an advanced two-way pipe call example here.

What is the difference between MOV and LEA?

It depends on the used assembler, because

mov ax,table_addr

in MASM works as

mov ax,word ptr[table_addr]

So it loads the first bytes from table_addr and NOT the offset to table_addr. You should use instead

mov ax,offset table_addr

or

lea ax,table_addr

which works the same.

lea version also works fine if table_addr is a local variable e.g.

some_procedure proc

local table_addr[64]:word

lea ax,table_addr

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

When I had this problem, I had literally just forgot to fill in a parameter value in the XAML of the code.

For some reason though, the exception would send me to the CS of the WPF program rather than the XAML. No idea why.

File path for project files?

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")

base directory + your filename

html select only one checkbox in a group

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
  <script>_x000D_
    angular.module('app', []).controller('appc', ['$scope',_x000D_
      function($scope) {_x000D_
        $scope.selected = 'male';_x000D_
      }_x000D_
    ]);_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body ng-app="app" ng-controller="appc">_x000D_
  <label>SELECTED: {{selected}}</label>_x000D_
  <div>_x000D_
    <input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male_x000D_
    <br>_x000D_
    <input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female_x000D_
    <br>_x000D_
    <input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to return value from function which has Observable subscription inside?

In the single-threaded,asynchronous,promise-oriented,reactive-trending world of javascript async/await is the imperative-style programmer's best friend:

(async()=>{

    const store = of("someValue");
    function getValueFromObservable () {
        return store.toPromise();
    }
    console.log(await getValueFromObservable())

})();

And in case store is a sequence of multiple values:

  const aiFrom = require('ix/asynciterable').from;
  (async function() {

     const store = from(["someValue","someOtherValue"]);
     function getValuesFromObservable () {
        return aiFrom(store);
     }
     for await (let num of getValuesFromObservable()) {
       console.log(num);
     }
  })();

How can I add an item to a IEnumerable<T> collection?

Sure, you can (I am leaving your T-business aside):

public IEnumerable<string> tryAdd(IEnumerable<string> items)
{
    List<string> list = items.ToList();
    string obj = "";
    list.Add(obj);

    return list.Select(i => i);
}

How to print last two columns using awk

Please try this out to take into account all possible scenarios:

awk '{print $(NF-1)"\t"$NF}'  file

or

awk 'BEGIN{OFS="\t"}' file

or

awk '{print $(NF-1), $NF} {print $(NF-1), $NF}' file

call a function in success of datatable ajax call

  "success" : function(data){
       //do stuff here
        fnCallback(data);
   }

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

there is a chrome extension 200ok its a web server for chrome just add that and select your folder

Show hide div using codebehind

I was having a problem where setting element.Visible = true in my code behind wasn't having any effect on the actual screen. The solution for me was to wrap the area of my page where I wanted to show the div in an ASP UpdatePanel, which is used to cause partial screen updates.

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

Having the element runat=server gave me access to it from the codebehind, and placing it in the UpdatePanel let it actually be updated on the screen.

List all indexes on ElasticSearch server?

here's another way just to see the indices in the db:

curl -sG somehost-dev.example.com:9200/_status --user "credentials:password" | sed 's/,/\n/g' | grep index | grep -v "size_in" | uniq


{ "index":"tmpdb"}

{ "index":"devapp"}

Forward host port to docker container

A simple but relatively insecure way would be to use the --net=host option to docker run.

This option makes it so that the container uses the networking stack of the host. Then you can connect to services running on the host simply by using "localhost" as the hostname.

This is easier to configure because you won't have to configure the service to accept connections from the IP address of your docker container, and you won't have to tell the docker container a specific IP address or host name to connect to, just a port.

For example, you can test it out by running the following command, which assumes your image is called my_image, your image includes the telnet utility, and the service you want to connect to is on port 25:

docker run --rm -i -t --net=host my_image telnet localhost 25

If you consider doing it this way, please see the caution about security on this page:

https://docs.docker.com/articles/networking/

It says:

--net=host -- Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick ip addr command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does not let the container reconfigure the host network stack — that would require --privileged=true — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like restart your computer. You should use this option with caution.

Height of an HTML select box (dropdown)

Actually you kind of can! Don't hassle with javascript... I was just stuck on the same thing for a website I'm making and if you increase the 'font-size' attribute in CSS for the tag then it automatically increases the height as well. Petty but it's something that bothers me a lot ha ha

Add my custom http header to Spring RestTemplate request / extend RestTemplate

You can pass custom http headers with RestTemplate exchange method as below.

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);

RestTemplate template = new RestTemplate();

ResponseEntity<RestResponse> respEntity = template
    .exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);

EDIT : Below is the updated code. This link has several ways of calling rest service with examples

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);

Mall[] resp = respEntity.getBody();

What is the Windows version of cron?

pycron is close match on Windows. The following entries are supported:

1    Minute (0-59)
2    Hour (2-24)
3    Day of month (1-31)
4    Month (1-12, Jan, Feb, etc)
5    Day of week (0-6) 0 = Sunday, 1 = Monday etc or Sun, Mon, etc)
6    User that the command will run as
7    Command to execute

How to run bootRun with spring profile via gradle task

I wanted it simple just to be able to call gradle bootRunDev like you without having to do any extra typing..

This worked for me - by first configuring it the bootRun in my task and then right after it running bootRun which worked fine for me :)

task bootRunDev {
    bootRun.configure {
        systemProperty "spring.profiles.active", 'Dev'
    }
}

bootRunDev.finalizedBy bootRun

Check if value is in select list with JQuery

Here is another similar option. In my case, I'm checking values in another box as I build a select list. I kept running into undefined values when I would compare, so I set my check this way:

if ( $("#select-box option[value='" + thevalue + "']").val() === undefined) { //do stuff }

I've no idea if this approach is more expensive.

Vertically aligning text next to a radio button

You could also try something like this:

_x000D_
_x000D_
input[type="radio"] {_x000D_
  margin-top: -1px;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
  <label  class="child"><input id = "warm" type="radio" name="weathertype" value="warm" checked> Warm<br></label>_x000D_
<label class="child1"><input id = "cold" type="radio" name="weathertype" value="cold" checked> Cold<br></label>
_x000D_
_x000D_
_x000D_

Example of Mockito's argumentCaptor

The steps in order to make a full check are:

Prepare the captor :

ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);

verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.

verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());

Get the argument passed to collaborator

SomeArgumentClass someArgument = messageCaptor.getValue();

someArgument can be used for assertions

How to make an empty div take space

Try adding &nbsp; to the empty items.

I don't understand why you're not using a <table> here, though? They will do this kind of stuff automatically.

Strange "java.lang.NoClassDefFoundError" in Eclipse

While this is a wild guess and may not be applicable in your specific situation, this could've saved me an hour or so.

In case you have "converted" a plain project into Java project (by editing .project file and adding appropriate tag), make sure you also have a proper specified - my project didn't get built even though Eclipse attempted to and run no builders (success!):

<buildSpec>
    <buildCommand>
        <name>org.eclipse.jdt.core.javabuilder</name>
        <arguments>
        </arguments>
    </buildCommand>
</buildSpec>

how to convert string to numerical values in mongodb

db.user.find().toArray().filter(a=>a.age>40)

How can I make a div stick to the top of the screen once it's been scrolled to?

Here's an example that uses jquery-visible plugin: http://jsfiddle.net/711p4em4/.

HTML:

<div class = "wrapper">
    <header>Header</header>
    <main>
        <nav>Stick to top</nav>
        Content
    </main>
    <footer>Footer</footer>
</div>

CSS:

* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #e2e2e2;
}

.wrapper > header,
.wrapper > footer {
    font: 20px/2 Sans-Serif;
    text-align: center;
    background-color: #0040FF;
    color: #fff;
}

.wrapper > main {
    position: relative;
    height: 500px;
    background-color: #5e5e5e;
    font: 20px/500px Sans-Serif;
    color: #fff;
    text-align: center;
    padding-top: 40px;
}

.wrapper > main > nav {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    font: 20px/2 Sans-Serif;
    color: #fff;
    text-align: center;
    background-color: #FFBF00;
}

.wrapper > main > nav.fixed {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
}

JS (include jquery-visible plugin):

(function($){

    /**
     * Copyright 2012, Digital Fusion
     * Licensed under the MIT license.
     * http://teamdf.com/jquery-plugins/license/
     *
     * @author Sam Sehnert
     * @desc A small plugin that checks whether elements are within
     *       the user visible viewport of a web browser.
     *       only accounts for vertical position, not horizontal.
     */
    var $w = $(window);
    $.fn.visible = function(partial,hidden,direction){

        if (this.length < 1)
            return;

        var $t        = this.length > 1 ? this.eq(0) : this,
            t         = $t.get(0),
            vpWidth   = $w.width(),
            vpHeight  = $w.height(),
            direction = (direction) ? direction : 'both',
            clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

        if (typeof t.getBoundingClientRect === 'function'){

            // Use this native browser method, if available.
            var rec = t.getBoundingClientRect(),
                tViz = rec.top    >= 0 && rec.top    <  vpHeight,
                bViz = rec.bottom >  0 && rec.bottom <= vpHeight,
                lViz = rec.left   >= 0 && rec.left   <  vpWidth,
                rViz = rec.right  >  0 && rec.right  <= vpWidth,
                vVisible   = partial ? tViz || bViz : tViz && bViz,
                hVisible   = partial ? lViz || rViz : lViz && rViz;

            if(direction === 'both')
                return clientSize && vVisible && hVisible;
            else if(direction === 'vertical')
                return clientSize && vVisible;
            else if(direction === 'horizontal')
                return clientSize && hVisible;
        } else {

            var viewTop         = $w.scrollTop(),
                viewBottom      = viewTop + vpHeight,
                viewLeft        = $w.scrollLeft(),
                viewRight       = viewLeft + vpWidth,
                offset          = $t.offset(),
                _top            = offset.top,
                _bottom         = _top + $t.height(),
                _left           = offset.left,
                _right          = _left + $t.width(),
                compareTop      = partial === true ? _bottom : _top,
                compareBottom   = partial === true ? _top : _bottom,
                compareLeft     = partial === true ? _right : _left,
                compareRight    = partial === true ? _left : _right;

            if(direction === 'both')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
            else if(direction === 'vertical')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
            else if(direction === 'horizontal')
                return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
        }
    };

})(jQuery);

$(function() {
    $(window).scroll(function() {
        $(".wrapper > header").visible(true) ?
            $(".wrapper > main > nav").removeClass("fixed") :
            $(".wrapper > main > nav").addClass("fixed");
    });
});

jQuery set radio button

The chosen answer works in this case.

But the question was about finding the element based on radiogroup and dynamic id, and the answer can also leave the displayed radio button unaffected.

This line does selects exactly what was asked for while showing the change on screen as well.

$('input:radio[name=cols][id='+ newcol +']').click();

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Try like this,

jQuery('.leaderMultiSelctdropdown').select2('data');

Prevent screen rotation on Android

Use AsyncTaskLoader to keep your data safe even if the activity changes, instead of using AsyncTask that is a better way to build apps than preventing screen rotation.

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

sometimes you just need to give the slave a kick too

try

stop slave;    
reset slave;    
start slave;    
show slave status;

quite often, slaves, they just get stuck guys :)

How to run a PowerShell script from a batch file

Small sample test.cmd

<# :
  @echo off
    powershell /nologo /noprofile /command ^
         "&{[ScriptBlock]::Create((cat """%~f0""") -join [Char[]]10).Invoke(@(&{$args}%*))}"
  exit /b
#>
Write-Host Hello, $args[0] -fo Green
#You programm...

TypeError: 'list' object is not callable in python

find out what you have assigned to 'list' by displaying it

>>> print(list)

if it has content, you have to clean it with

>>> del list

now display 'list' again and expect this

<class 'list'>

Once you see this, you can proceed with your copy.

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

Get the selected value in a dropdown using jQuery.

$('#availability').find('option:selected').val() // For Value 
$('#availability').find('option:selected').text() // For Text
or 
$('#availability option:selected').val() // For Value 
$('#availability option:selected').text() // For Text

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

Remove the parentheses:

List<string> nameslist = new List<string> {"one", "two", "three"};

How to format a number 0..9 to display with 2 digits (it's NOT a date)

You can use:

String.format("%02d", myNumber)

See also the javadocs

Count number of matches of a regex in Javascript

(('a a a').match(/b/g) || []).length; // 0
(('a a a').match(/a/g) || []).length; // 3

Based on https://stackoverflow.com/a/48195124/16777 but fixed to actually work in zero-results case.

How do I convert a org.w3c.dom.Document object to a String?

use some thing like

import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

//method to convert Document to String
public String getStringFromDocument(Document doc)
{
    try
    {
       DOMSource domSource = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(domSource, result);
       return writer.toString();
    }
    catch(TransformerException ex)
    {
       ex.printStackTrace();
       return null;
    }
} 

Composer install error - requires ext_curl when it's actually enabled

For anyone who encounters this issue on Windows i couldn't find my answer on google at all. I just tried running composer require ext-curl and this worked. Alternatively add the following in your composer.json file:

"require": {
"ext-curl": "^7.3"
}

View a file in a different Git branch without changing branches

A simple, newbie friendly way for looking into a file: git gui browser <branch> which lets you explore the contents of any file.

It's also there in the File menu of git gui. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

Binding objects defined in code-behind

I was having this exact same problem but mine wasn't because I was setting a local variable... I was in a child window, and I needed to set a relative DataContext which I just added to the Window XAML.

<Window x:Class="Log4Net_Viewer.LogItemWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    Title="LogItemWindow" Height="397" Width="572">

How can I print out C++ map values?

If your compiler supports (at least part of) C++11 you could do something like:

for (auto& t : myMap)
    std::cout << t.first << " " 
              << t.second.first << " " 
              << t.second.second << "\n";

For C++03 I'd use std::copy with an insertion operator instead:

typedef std::pair<string, std::pair<string, string> > T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.first << " " << t.second.first << " " << t.second.second;
}

// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Remove spaces from std::string in C++

The best thing to do is to use the algorithm remove_if and isspace:

remove_if(str.begin(), str.end(), isspace);

Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:

str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:

template<typename T, typename P>
T remove_if(T beg, T end, P pred)
{
    T dest = beg;
    for (T itr = beg;itr != end; ++itr)
        if (!pred(*itr))
            *(dest++) = *itr;
    return dest;
}

MySQL: can't access root account

You can use the init files. Check the MySQL official documentation on How to Reset the Root Password (including comments for alternative solutions).

So basically using init files, you can add any SQL queries that you need for fixing your access (such as GRAND, CREATE, FLUSH PRIVILEGES, etc.) into init file (any file).

Here is my example of recovering root account:

echo "CREATE USER 'root'@'localhost' IDENTIFIED BY 'root';" > your_init_file.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> your_init_file.sql 
echo "FLUSH PRIVILEGES;" >> your_init_file.sql

and after you've created your file, you can run:

killall mysqld
mysqld_safe --init-file=$PWD/your_init_file.sql

then to check if this worked, press Ctrl+Z and type: bg to run the process from the foreground into the background, then verify your access by:

mysql -u root -proot
mysql> show grants;
+-------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                   |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' |

See also:

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

Place your config file into src/main/resources/app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

Place your config file into src/test/resources/test-app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

How to write a large buffer into a binary file in C++, fast?

If you copy something from disk A to disk B in explorer, Windows employs DMA. That means for most of the copy process, the CPU will basically do nothing other than telling the disk controller where to put, and get data from, eliminating a whole step in the chain, and one that is not at all optimized for moving large amounts of data - and I mean hardware.

What you do involves the CPU a lot. I want to point you to the "Some calculations to fill a[]" part. Which I think is essential. You generate a[], then you copy from a[] to an output buffer (thats what fstream::write does), then you generate again, etc.

What to do? Multithreading! (I hope you have a multi-core processor)

  • fork.
  • Use one thread to generate a[] data
  • Use the other to write data from a[] to disk
  • You will need two arrays a1[] and a2[] and switch between them
  • You will need some sort of synchronization between your threads (semaphores, message queue, etc.)
  • Use lower level, unbuffered, functions, like the the WriteFile function mentioned by Mehrdad

Are there benefits of passing by pointer over passing by reference in C++?

Most of the answers here fail to address the inherent ambiguity in having a raw pointer in a function signature, in terms of expressing intent. The problems are the following:

  • The caller does not know whether the pointer points to a single objects, or to the start of an "array" of objects.

  • The caller does not know whether the pointer "owns" the memory it points to. IE, whether or not the function should free up the memory. (foo(new int) - Is this a memory leak?).

  • The caller does not know whether or not nullptr can be safely passed into the function.

All of these problems are solved by references:

  • References always refer to a single object.

  • References never own the memory they refer to, they are merely a view into memory.

  • References can't be null.

This makes references a much better candidate for general use. However, references aren't perfect - there are a couple of major problems to consider.

  • No explicit indirection. This is not a problem with a raw pointer, as we have to use the & operator to show that we are indeed passing a pointer. For example, int a = 5; foo(a); It is not clear at all here that a is being passed by reference and could be modified.
  • Nullability. This weakness of pointers can also be a strength, when we actually want our references to be nullable. Seeing as std::optional<T&> isn't valid (for good reasons), pointers give us that nullability you want.

So it seems that when we want a nullable reference with explicit indirection, we should reach for a T* right? Wrong!

Abstractions

In our desperation for nullability, we may reach for T*, and simply ignore all of the shortcomings and semantic ambiguity listed earlier. Instead, we should reach for what C++ does best: an abstraction. If we simply write a class that wraps around a pointer, we gain the expressiveness, as well as the nullability and explicit indirection.

template <typename T>
struct optional_ref {
  optional_ref() : ptr(nullptr) {}
  optional_ref(T* t) : ptr(t) {}
  optional_ref(std::nullptr_t) : ptr(nullptr) {}

  T& get() const {
    return *ptr;
  }

  explicit operator bool() const {
    return bool(ptr);
  }

private:
  T* ptr;
};

This is the most simple interface I could come up with, but it does the job effectively. It allows for initializing the reference, checking whether a value exists and accessing the value. We can use it like so:

void foo(optional_ref<int> x) {
  if (x) {
    auto y = x.get();
    // use y here
  }
}

int x = 5;
foo(&x); // explicit indirection here
foo(nullptr); // nullability

We have acheived our goals! Let's now see the benefits, in comparison to the raw pointer.

  • The interface shows clearly that the reference should only refer to one object.
  • Clearly it does not own the memory it refers to, as it has no user defined destructor and no method to delete the memory.
  • The caller knows nullptr can be passed in, since the function author explicitly is asking for an optional_ref

We could make the interface more complex from here, such as adding equality operators, a monadic get_or and map interface, a method that gets the value or throws an exception, constexpr support. That can be done by you.

In conclusion, instead of using raw pointers, reason about what those pointers actually mean in your code, and either leverage a standard library abstraction or write your own. This will improve your code significantly.

Find number of decimal places in decimal value regardless of culture

Most people here seem to be unaware that decimal considers trailing zeroes as significant for storage and printing.

So 0.1m, 0.10m and 0.100m may compare as equal, they are stored differently (as value/scale 1/1, 10/2 and 100/3, respectively), and will be printed as 0.1, 0.10 and 0.100, respectively, by ToString().

As such, the solutions that report "too high a precision" are actually reporting the correct precision, on decimal's terms.

In addition, math-based solutions (like multiplying by powers of 10) will likely be very slow (decimal is ~40x slower than double for arithmetic, and you don't want to mix in floating-point either because that's likely to introduce imprecision). Similarly, casting to int or long as a means of truncating is error-prone (decimal has a much greater range than either of those - it's based around a 96-bit integer).

While not elegant as such, the following will likely be one of the fastest way to get the precision (when defined as "decimal places excluding trailing zeroes"):

public static int PrecisionOf(decimal d) {
  var text = d.ToString(System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0');
  var decpoint = text.IndexOf('.');
  if (decpoint < 0)
    return 0;
  return text.Length - decpoint - 1;
}

The invariant culture guarantees a '.' as decimal point, trailing zeroes are trimmed, and then it's just a matter of seeing of how many positions remain after the decimal point (if there even is one).

Edit: changed return type to int

How to update Pandas from Anaconda and is it possible to use eclipse with this last

Simply type conda update pandas in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory). See this document for a detailed instruction.

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

How to downgrade tensorflow, multiple versions possible?

You can try to use the options of --no-cache-dir together with -I to overwrite the cache of the previous version and install the new version. For example:

pip3 install --no-cache-dir -I tensorflow==1.1

Then use the following command to check the version of tensorflow:

python3 -c ‘import tensorflow as tf; print(tf.__version__)’

It should show the right version got installed.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

We solved the problem by stopping the FinalizerWatchdogDaemon.

public static void fix() {
    try {
        Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");

        Method method = clazz.getSuperclass().getDeclaredMethod("stop");
        method.setAccessible(true);

        Field field = clazz.getDeclaredField("INSTANCE");
        field.setAccessible(true);

        method.invoke(field.get(null));

    }
    catch (Throwable e) {
        e.printStackTrace();
    }
}

You can call the method in Application's lifecycle, like attachBaseContext(). For the same reason, you also can specific the phone's manufacture to fix the problem, it's up to you.

creating batch script to unzip a file without additional zip tools

If you have PowerShell 5.0 or higher (pre-installed with Windows 10 and Windows Server 2016):

powershell Expand-Archive your.zip -DestinationPath your_destination

How do you search an amazon s3 bucket?

Just a note to add on here: it's now 3 years later, yet this post is top in Google when you type in "How to search an S3 Bucket."

Perhaps you're looking for something more complex, but if you landed here trying to figure out how to simply find an object (file) by it's title, it's crazy simple:

open the bucket, select "none" on the right hand side, and start typing in the file name.

http://docs.aws.amazon.com/AmazonS3/latest/UG/ListingObjectsinaBucket.html

Variable length (Dynamic) Arrays in Java

I disagree with the previous answers suggesting ArrayList, because ArrayList is not a Dynamic Array but a List backed by an array. The difference is that you cannot do the following:

ArrayList list = new ArrayList(4);
list.put(3,"Test");

It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by @randy-lance

Writing String to Stream and reading it back does not work

You need to reset the stream to the beginning:

stringAsStream.Seek(0, SeekOrigin.Begin);
Console.WriteLine("Differs from:\t" + (char)stringAsStream.ReadByte());

This can also be done by setting the Position property to 0:

stringAsStream.Position = 0

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

ACCESSING LOCAL WEBSITE WITH IIS without Physical Path Authentication

  1. Make sure you have installed URL Rewrite to your IIS Manager

enter image description here

  1. Open the URL Rewrite application then navigate to Inbound Rules>Import Rules

enter image description here

  1. To import the rule, click the browse button then locate your .htaccess file then click import button

enter image description here

  1. The text labeled with red are errors that are not accepted by IIS, so you have to remove them by clicking the errors in the converted rules and remove the text from the rewrite rules. Once you have get rid of the errors Click the APPLY button located at the top right corner. Then try to access your site without engaging users into the pool auth.

enter image description here

I hope it helps. That's what I did.

Enter export password to generate a P12 certificate

The selected answer apparently does not work anymore in 2019 (at least for me).

I was trying to export a certificate using openssl (version 1.1.0) and the parameter -password doesn't work.

According to that link in the original answer (the same info is in man openssl), openssl has two parameter for passwords and they are -passin for the input parts and -passout for output files.

For the -export command, I used -passin for the password of my key file and -passout to create a new password for my P12 file.

So the complete command without any prompt was like below:

openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass:keypassphrase -passout pass:certificatepassword

If you does not want a password, you can use pass: like below:

openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass: -passout pass:

It will works fine with a key without password and the output certificate will be created without password too.

Reset IntelliJ UI to Default

The existing answers are outdated. This is now doable from the menu:

Window -> Restore Default Layout (shift+f12)

Make sure nothing is currently running, as the Run/Debug window layout will not be reset otherwise.

How to get the jQuery $.ajax error response text?

The best simple approach :

error: function (xhr) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}

Location of ini/config files in linux/unix?

(1) No (unfortunately). Edit: The other answers are right, per-user configuration is usually stored in dot-files or dot-directories in the users home directory. Anything above user level often is a lot of guesswork.

(2) System-wide ini file -> user ini file -> environment -> command line options (going from lowest to highest precedence)

Semaphore vs. Monitors - what's the difference?

Semaphore allows multiple threads (up to a set number) to access a shared object. Monitors allow mutually exclusive access to a shared object.

Monitor

Semaphore

Failed to locate the winutils binary in the hadoop binary path

Download desired version of hadoop folder (Say if you are installing spark on Windows then hadoop version for which your spark is built for) from this link as zip.

Extract the zip to desired directory. You need to have directory of the form hadoop\bin (explicitly create such hadoop\bin directory structure if you want) with bin containing all the files contained in bin folder of the downloaded hadoop. This will contain many files such as hdfs.dll, hadoop.dll etc. in addition to winutil.exe.

Now create environment variable HADOOP_HOME and set it to <path-to-hadoop-folder>\hadoop. Then add ;%HADOOP_HOME%\bin; to PATH environment variable.

Open a "new command prompt" and try rerunning your command.

Java: How to convert String[] to List or Set

If you really want to use a set:

String[] strArray = {"foo", "foo", "bar"};  
Set<String> mySet = new HashSet<String>(Arrays.asList(strArray));
System.out.println(mySet);

output:

[foo, bar]

How do I change the default port (9000) that Play uses when I execute the "run" command?

I did this. sudo is necessary.

$ sudo play debug -Dhttp.port=80
...
[MyPlayApp] $ run

EDIT: I had problems because of using sudo so take care. Finally I cleaned up the project and I haven't used that trick anymore.

How can I get Android Wifi Scan Results into a list?

Wrap an ArrayAdapter around your List<ScanResult>. Override getView() to populate your rows with the ScanResult data. Here is a free excerpt from one of my books that covers how to create custom ArrayAdapters like this.

How to keep keys/values in same order as declared?

You can do the same thing which i did for dictionary.

Create a list and empty dictionary:

dictionary_items = {}
fields = [['Name', 'Himanshu Kanojiya'], ['email id', '[email protected]']]
l = fields[0][0]
m = fields[0][1]
n = fields[1][0]
q = fields[1][1]
dictionary_items[l] = m
dictionary_items[n] = q
print dictionary_items

.gitignore is ignored by Git

OK, so in my case the accepted solution did not work, and what worked is described here:

Is Visual Studio 2013 ignoring your .gitignore file?

In short:

  • Close Visual Studio.
  • Navigate to your .git folder
  • Delete ms-persist.xml
  • Restart Visual Studio

Javascript (+) sign concatenates instead of giving sum of variables

Care must be taken that i is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.

It is a good practice to initialize variables of declaration:

  • In case of integers, var num = 0;
  • In case of strings, var str = "";

Even if your i variable is integer, + operator can perform concatenation instead of addition.

In your problem's case, you have supposed that i = 1, in order to get 2 in addition with 1 try using (i-1+2). Use of ()-parenthesis will not be necessary.

- (minus operator) cannot be misunderstood and you will not get unexpected result/s.

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

There are 3 things you need.

  1. You need to oAuth with the owner of those photos. (with the 'user_photos' extended permission)

  2. You need the access token (which you get returned in the URL box after the oAuth is done.)

  3. When those are complete you can then access the photos like so https://graph.facebook.com/me?access_token=ACCESS_TOKEN

You can find all of the information in more detail here: http://developers.facebook.com/docs/authentication

Unable to find valid certification path to requested target - error even after cert imported

I am working on a tutorial for REST web services at www.udemy.com (REST Java Web Services). The example in the tutorial said that in order to have SSL, we must have a folder called "trust_store" in my eclipse "client" project that should contain a "key store" file (we had a "client" project to call the service, and "service" project that contained the REST web service - 2 projects in the same eclipse workspace, one the client, the other the service). To keep things simple, they said to copy "keystore.jks" from the glassfish app server (glassfish\domains\domain1\config\keystore.jks) we are using and put it into this "trust_store" folder that they had me make in the client project. That seems to make sense: the self-signed certs in the server's key_store would correspond to the certs in the client trust_store. Now, doing this, I was getting the error that the original post mentions. I have googled this and read that the error is due to the "keystore.jks" file on the client not containing a trusted/signed certificate, that the certificate it finds is self-signed.

To keep things clear, let me say that as I understand it, the "keystore.jks" contains self-signed certs, and the "cacerts.jks" file contains CA certs (signed by the CA). The "keystore.jks" is the "keystore" and the "cacerts.jks" is the "trust store". As "Bruno", a commenter, says above, "keystore.jks" is local, and "cacerts.jks" is for remote clients.

So, I said to myself, hey, glassfish also has the "cacerts.jks" file, which is glassfish's trust_store file. cacerts.jsk is supposed to contain CA certificates. And apparently I need my trust_store folder to contain a key store file that has at least one CA certificate. So, I tried putting the "cacerts.jks" file in the "trust_store" folder I had made, on my client project, and changing the VM properties to point to "cacerts.jks" instead of "keystore.jks". That got rid of the error. I guess all it needed was a CA cert to work.

This may not be ideal for production, or even for development beyond just getting something to work. For instance you could probably use "keytool" command to add CA certs to the "keystore.jks" file in the client. But anyway hopefully this at least narrows down the possible scenarios that could be going on here to cause the error.

ALSO: my approach seemed to be useful for the client (server cert added to client trust_store), it looks like the comments above to resolve the original post are useful for the server (client cert added to server trust_store). Cheers.

Eclipse project setup:

  • MyClientProject
  • src
  • test
  • JRE System Library
  • ...
  • trust_store
    ---cacerts.jks ---keystore.jks

Snippet from MyClientProject.java file:

static {
  // Setup the trustStore location and password
  System.setProperty("javax.net.ssl.trustStore","trust_store/cacerts.jks");
  // comment out below line
  System.setProperty("javax.net.ssl.trustStore","trust_store/keystore.jks");
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
  //System.setProperty("javax.net.debug", "all");

  // for localhost testing only
  javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
          return hostname.equals("localhost");
        }

  });
}

Print the stack trace of an exception

Apache commons provides utility to convert the stack trace from throwable to string.

Usage:

ExceptionUtils.getStackTrace(e)

For complete documentation refer to https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html

How to find the index of an element in an int array?

static int[] getIndex(int[] data, int number) {
    int[] positions = new int[data.length];
    if (data.length > 0) {
        int counter = 0;
        for(int i =0; i < data.length; i++) {
            if(data[i] == number){
                positions[counter] = i;
                counter++;
            }
        }
    }
    return positions;
}

How to display a list using ViewBag

i had the same problem and i search and search .. but got no result.
so i put my brain in over drive. and i came up with the below solution. try this in the View Page

at the head of the page add this code

 @{
      var Lst = ViewBag.data as IEnumerable<MyProject.Models.Person>;
    }

to display the particular attribute use the below code

@Lst.FirstOrDefault().FirstName

in your case use below code.

<td>@Lst.FirstOrDefault().FirstName </td>  

Hope this helps...

PHP header(Location: ...): Force URL change in address bar

Do not use any white space. I had the same issue. Then I removed white space like:

header("location:index.php"); or header('location:index.php');

Then it worked.

How can I refresh a page with jQuery?

As the question is generic, let's try to sum up possible solutions for the answer:

Simple plain JavaScript Solution:

The easiest way is a one line solution placed in an appropriate way:

location.reload();

What many people are missing here, because they hope to get some "points" is that the reload() function itself offers a Boolean as a parameter (details: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload).

The Location.reload() method reloads the resource from the current URL. Its optional unique parameter is a Boolean, which, when it is true, causes the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

This means there are two ways:

Solution1: Force reloading the current page from the server

location.reload(true);

Solution2: Reloading from cache or server (based on browser and your config)

location.reload(false);
location.reload();

And if you want to combine it with jQuery an listening to an event, I would recommend using the ".on()" method instead of ".click" or other event wrappers, e.g. a more proper solution would be:

$('#reloadIt').on('eventXyZ', function() {
    location.reload(true);
});

What are C++ functors and their uses?

Name "functor" has been traditionaly used in category theory long before C++ appeared on the scene. This has nothing to do with C++ concept of functor. It's better to use name function object instead of what we call "functor" in C++. This is how other programming languages call similar constructs.

Used instead of plain function:

Features:

  • Function object may have state
  • Function object fits into OOP (it behaves like every other object).

Cons:

  • Brings more complexity to the program.

Used instead of function pointer:

Features:

  • Function object often may be inlined

Cons:

  • Function object can not be swapped with other function object type during runtime (at least unless it extends some base class, which therefore gives some overhead)

Used instead of virtual function:

Features:

  • Function object (non-virtual) doesn't require vtable and runtime dispatching, thus it is more efficient in most cases

Cons:

  • Function object can not be swapped with other function object type during runtime (at least unless it extends some base class, which therefore gives some overhead)

IIS w3svc error

Make sure these 2 services running and their startup type is automatic.If they disabled and not running right click on them and go to properties and change from there.

  1. Windows process activation service
  2. Worldwide web publishing service.

Attach parameter to button.addTarget action in Swift

This is more of an important comment. Sharing references of sytanx that is acceptable out of the box. For hack solutions look at other answers.

Per Apple's docs, Action Method Definitions have to be either one of these three. Anything else is unaccepted.

@IBAction func doSomething()
@IBAction func doSomething(sender: UIButton)
@IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)

How is attr_accessible used in Rails 4?

An update for Rails 5:

gem 'protected_attributes' 

doesn't seem to work anymore. But give:

gem 'protected_attributes_continued'

a try.

Selecting option by text content with jQuery

I know this question is too old, but still, I think this approach would be cleaner:

cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);

In this case you wont need to go over the entire options with each(). Although by that time prop() didn't exist so for older versions of jQuery use attr().


UPDATE

You have to be certain when using contains because you can find multiple options, in case of the string inside cat matches a substring of a different option than the one you intend to match.

Then you should use:

cat = $.URLDecode(cat);
$('#cbCategory option')
    .filter(function(index) { return $(this).text() === cat; })
    .prop('selected', true);

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  }
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  }
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;
  }

After that, I got identical display input[password]

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

This error might be also for plugin versions. You can fix it in the .POM file like the followings:

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

How do I determine the current operating system with Node.js

I was facing the same issue running my node js code on Windows VM on mac machine. The following code did the trick.

Replace

process.platform == 'win32'

with

const os = require('os');

os.platform() == 'win32';

Windows command to get service status?

according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST but i can't get it to work on by XP box. I'm sure there's some WMI that will give you the list.

Angular 2: 404 error occur when I refresh through the browser

For people reading this that use Angular 2 rc4 or later, it appears LocationStrategy has been moved from router to common. You'll have to import it from there.

Also note the curly brackets around the 'provide' line.

main.ts

// Imports for loading & configuring the in-memory web api
import { XHRBackend } from '@angular/http';

// The usual bootstrapping imports
import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }         from './app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
import { Location, LocationStrategy, HashLocationStrategy} from '@angular/common';

bootstrap(AppComponent, [
    APP_ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

WCF change endpoint address at runtime

So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this:

EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn);   
var client = new EchoServiceClient(address); 
litResponse.Text = client.SendEcho("Hello World"); 
client.Close();

Actual working final version by valamas

EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri("http://id.web/Services/EchoService.svc");
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.SendEcho("Hello World");
client.Close(); 

Removing the title text of an iOS UIBarButtonItem

This worked for me in iOS 7+:

In viewDidLoad:

self.navigationItem.backBarButtonItem.title = @" ";

Yes, that's a space between the quotes.

how to implement login auth in node.js

@alessioalex answer is a perfect demo for fresh node user. But anyway, it's hard to write checkAuth middleware into all routes except login, so it's better to move the checkAuth from every route to one entry with app.use. For example:

function checkAuth(req, res, next) {
  // if logined or it's login request, then go next route
  if (isLogin || (req.path === '/login' && req.method === 'POST')) {
    next()
  } else {
    res.send('Not logged in yet.')
  }
}

app.use('/', checkAuth)

What is the difference between == and equals() in Java?

Just remember that .equals(...) has to be implemented by the class you are trying to compare. Otherwise, there isn't much of a point; the version of the method for the Object class does the same thing as the comparison operation: Object#equals.

The only time you really want to use the comparison operator for objects is wen you are comparing Enums. This is because there is only one instance of an Enum value at a time. For instance, given the enum

enum FooEnum {A, B, C}

You will never have more than one instance of A at a time, and the same for B and C. This means that you can actually write a method like so:

public boolean compareFoos(FooEnum x, FooEnum y)
{
    return (x == y);
}

And you will have no problems whatsoever.

.NET 4.0 has a new GAC, why?

I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):

Mark Miller said... June 28, 2010 12:13 PM

Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.

For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.

This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.

It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.

Hope it helps future readers.

Circular (or cyclic) imports in Python

Module a.py :

import b
print("This is from module a")

Module b.py

import a
print("This is from module b")

Running "Module a" will output:

>>> 
'This is from module a'
'This is from module b'
'This is from module a'
>>> 

It output this 3 lines while it was supposed to output infinitival because of circular importing. What happens line by line while running"Module a" is listed here:

  1. The first line is import b. so it will visit module b
  2. The first line at module b is import a. so it will visit module a
  3. The first line at module a is import b but note that this line won't be executed again anymore, because every file in python execute an import line just for once, it does not matter where or when it is executed. so it will pass to the next line and print "This is from module a".
  4. After finish visiting whole module a from module b, we are still at module b. so the next line will print "This is from module b"
  5. Module b lines are executed completely. so we will go back to module a where we started module b.
  6. import b line have been executed already and won't be executed again. the next line will print "This is from module a" and program will be finished.

How to install Visual Studio 2015 on a different drive

Run the installer from command line with argument /CustomInstallPath InstallationDirectory

See more command-line parameters and other installation information.

Note: this won't change location of all files, but only of those which can be (by design) installed onto different location. Be warned that there is many shared components which will be installed into shared repositories on drive C: without any possibility to change their path (unless you do some hacking using mklink /j (directory junction, i.e."hard link for folder"), but it is questionable whether it is worth it, because any Visual Studio updates will break those hard links. This is confirmed by people who tried that, although on Visual Studio 2012.)


Update: per recent comment, uninstallation of Visual Studio might be required before the above applies. Uninstallation command is like this: vs_community_ENU.exe /uninstall /force

How can I delete all of my Git stashes at once?

To delete all stashes older than 40 days, use:

git reflog expire --expire-unreachable=40.days refs/stash

Add --dry-run to see which stashes are deleted.

See https://stackoverflow.com/a/44829516/946850 for an explanation and much more detail.

JavaScript Editor Plugin for Eclipse

JavaScript that allows for syntax checking

JSHint-Eclipse

and autosuggestions for .js files in Eclipse?

  1. Use JSDoc more as JSDT has nice support for the standard, so you will get more suggestions for your own code.
  2. There is new TernIDE that provide additional hints for .js and AngulatJS .html. Get them together as Anide from http://www.nodeclipse.org/updates/anide/

As Nodeclipse lead, I am always looking for what is available in Eclipse ecosystem. Nodeclipse site has even more links, and I am inviting to collaborate on the JavaScript tools on GitHub

Delete files or folder recursively on Windows CMD

dir /b %temp% >temp.list
for /f "delims=" %%a in (temp.list) do call rundll32.exe advpack.dll,DelNodeRunDLL32 "%temp%\%%a"

How can I represent an 'Enum' in Python?

This solution is a simple way of getting a class for the enumeration defined as a list (no more annoying integer assignments):

enumeration.py:

import new

def create(class_name, names):
    return new.classobj(
        class_name, (object,), dict((y, x) for x, y in enumerate(names))
    )

example.py:

import enumeration

Colors = enumeration.create('Colors', (
    'red',
    'orange',
    'yellow',
    'green',
    'blue',
    'violet',
))

Count work days between two dates

For workdays, Monday to Friday, you can do it with a single SELECT, like this:

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2008/10/01'
SET @EndDate = '2008/10/31'


SELECT
   (DATEDIFF(dd, @StartDate, @EndDate) + 1)
  -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
  -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)

If you want to include holidays, you have to work it out a bit...

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

And yet another option: https://github.com/apptik/jus

  • It is modular like Volley, but more extended and documentation is improving, supporting different HTTP stacks and converters out of the box
  • It has a module to generate server API interface mappings like Retrofit
  • It also has JavaRx support

And many other handy features like markers, transformers, etc.

highlight the navigation menu for the current page

It seems to me that you need current code as this ".menu-current css", I am asking the same code that works like a charm, You could try something like this might still be some configuration

a:link, a:active {
    color: blue;
    text-decoration: none;
}

a:visited {
    color: darkblue;
    text-decoration: none;
}

a:hover {
    color: blue;
    text-decoration: underline;
}

div.menuv {
    float: left;
    width: 10em;
    padding: 1em;
    font-size: small;
}


div.menuv ul, div.menuv li, div.menuv .menuv-current li {
    margin: 0;
    padding: 0;
    list-style: none;
    margin-bottom: 5px;
    font-weight: normal;
}

div.menuv ul ul {
    padding-left: 12px;
}

div.menuv a:link, div.menuv a:visited, div.menuv a:active, div.menuv a:hover {
    display: block;
    text-decoration: none;
    padding: 2px 2px 2px 3px;
    border-bottom: 1px dotted #999999;
}

div.menuv a:hover, div.menuv .menuv-current li a:hover {
    padding: 2px 0px 2px 1px;
    border-left: 2px solid green;
    border-right: 2px solid green;
}

div.menuv .menuv-current {
    font-weight: bold;
}

div.menuv .menuv-current a:hover {
    padding: 2px 2px 2px 3px;
    border-left: none;
    border-right: none;
    border-bottom: 1px dotted #999999;
    color: darkblue;
}

Close Window from ViewModel

You can create new Event handler in the ViewModel like this.

public event EventHandler RequestClose;

    protected void OnRequestClose()
    {
        if (RequestClose != null)
            RequestClose(this, EventArgs.Empty);
    }

Then Define RelayCommand for ExitCommand.

private RelayCommand _CloseCommand;
    public ICommand CloseCommand
    {
        get
        {
            if(this._CloseCommand==null)
                this._CloseCommand=new RelayCommand(CloseClick);
            return this._CloseCommand;
        }
    }

    private void CloseClick(object obj)
    {
        OnRequestClose();
    }

Then In XAML file set

<Button Command="{Binding CloseCommand}" />

Set the DataContext in the xaml.cs File and Subscribe to the event we created.

public partial class MainWindow : Window
{
    private ViewModel mainViewModel = null;
    public MainWindow()
    {
        InitializeComponent();
        mainViewModel = new ViewModel();
        this.DataContext = mainViewModel;
        mainViewModel.RequestClose += delegate(object sender, EventArgs args) { this.Close(); };
    }
}

Does the join order matter in SQL?

Oracle optimizer chooses join order of tables for inner join. Optimizer chooses the join order of tables only in simple FROM clauses . U can check the oracle documentation in their website. And for the left, right outer join the most voted answer is right. The optimizer chooses the optimal join order as well as the optimal index for each table. The join order can affect which index is the best choice. The optimizer can choose an index as the access path for a table if it is the inner table, but not if it is the outer table (and there are no further qualifications).

The optimizer chooses the join order of tables only in simple FROM clauses. Most joins using the JOIN keyword are flattened into simple joins, so the optimizer chooses their join order.

The optimizer does not choose the join order for outer joins; it uses the order specified in the statement.

When selecting a join order, the optimizer takes into account: The size of each table The indexes available on each table Whether an index on a table is useful in a particular join order The number of rows and pages to be scanned for each table in each join order

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

First check - is the working directory the directory that the application is running in:

  • Right-click on your project and select Properties.
  • Click the Debug tab.
  • Confirm that the Working directory is either empty or equal to the bin\debug directory.

If this isn't the problem, then ask if Autodesk.Navisworks.Timeliner.dll is requiring another DLL which is not there. If Timeliner.dll is not a .NET assembly, you can determine the required imports using the command utility DUMPBIN.

dumpbin /imports Autodesk.Navisworks.Timeliner.dll

If it is a .NET assembly, there are a number of tools that can check dependencies.

Reflector has already been mentioned, and I use JustDecompile from Telerik.


Also see this question

Getting Textbox value in Javascript

<script type="text/javascript" runat="server">
 public void Page_Load(object Sender, System.EventArgs e)
    {
        double rad=0.0;
        TextBox1.Attributes.Add("Visible", "False");
        if (TextBox1.Text != "") 
        rad = Convert.ToDouble(TextBox1.Text);    
        Button1.Attributes.Add("OnClick","alert("+ rad +")");
    }
</script>

<asp:Button ID="Button1" runat="server" Text="Diameter" 
            style="z-index: 1; left: 133px; top: 181px; position: absolute" />
<asp:TextBox ID="TextBox1" Visible="True" Text="" runat="server" 
            AutoPostBack="true" 
            style="z-index: 1; left: 134px; top: 133px; position: absolute" ></asp:TextBox>

use the help of this, hope it will be usefull

Load local javascript file in chrome for testing?

To load local resources in Chrome when just using your local computer and not using a webserver you need to add the --allow-file-access-from-files flag.

You can have a shortcut to Chrome that allows files access and one that does not.

Create a shortcut for Chrome on the desktop, right click on shortcut, select properties. In the dialog box that opens find the target for the short cut and add the parameter after chrome.exe leaving a space

eg C:\PATH TO\chrome.exe --allow-file-access-from-files

This shortcut will allow access to files without affecting any other shortcut to Chrome you have.

When you open Chrome with this shortcut it should allow local resources to be loaded using HTML5 and the filesystem api

Git Checkout warning: unable to unlink files, permission denied

All you need to do is provide permissions, run the command below from the root of your project:

    chmod ug+w <directory path>

How to properly add cross-site request forgery (CSRF) token using PHP

The variable $token is not being retrieved from the session when it's in there

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

Using ZXing to create an Android barcode scanning app

If you want to include into your code and not use the IntentIntegrator that the ZXing library recommend, you can use some of these ports:

I use the first, and it works perfectly! It has a sample project to try it on.

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Following worked for me from the command line:

aapt dump badging myapp.apk

NOTE: aapt.exe is found in a build-tools sub-folder of SDK. For example:

<sdk_path>/build-tools/23.0.2/aapt.exe

Populating a data frame in R in a loop

You could do it like this:

 iterations = 10
 variables = 2

 output <- matrix(ncol=variables, nrow=iterations)

 for(i in 1:iterations){
  output[i,] <- runif(2)

 }

 output

and then turn it into a data.frame

 output <- data.frame(output)
 class(output)

what this does:

  1. create a matrix with rows and columns according to the expected growth
  2. insert 2 random numbers into the matrix
  3. convert this into a dataframe after the loop has finished.

Laravel, sync() - how to sync an array and also pass additional pivot fields?

In order to sync multiple models along with custom pivot data, you need this:

$user->roles()->sync([ 
    1 => ['expires' => true],
    2 => ['expires' => false],
    ...
]);

Ie.

sync([
    related_id => ['pivot_field' => value],
    ...
]);

edit

Answering the comment:

$speakers  = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData  = array_combine($speakers, $pivotData);

$user->roles()->sync($syncData);