Programs & Examples On #Shelveset

Command to get nth line of STDOUT

Try this sed version:

ls -l | sed '2 ! d'

It says "delete all the lines that aren't the second one".

Email address validation using ASP.NET MVC data type attributes

[RegularExpression(@"^[A-Za-z0-9]+@([a-zA-Z]+\\.)+[a-zA-Z]{2,6}]&")]

close fancy box from function from within open 'fancybox'

i had the same issues a longtime then i got the solution by the below code. please use

parent.jQuery.fancybox.close()

Get year, month or day from numpy datetime64

As datetime is not stable in numpy I would use pandas for this:

In [52]: import pandas as pd

In [53]: dates = pd.DatetimeIndex(['2010-10-17', '2011-05-13', "2012-01-15"])

In [54]: dates.year
Out[54]: array([2010, 2011, 2012], dtype=int32)

Pandas uses numpy datetime internally, but seems to avoid the shortages, that numpy has up to now.

How do you add an SDK to Android Studio?

You can change from the "build.gradle" file the line:

compileSdkVersion 18

to the sdk that you want to be used.

How to write log base(2) in c/c++

Simple math:

    log2 (x) = logy (x) / logy (2)

where y can be anything, which for standard log functions is either 10 or e.

UTF-8 problems while reading CSV file with fgetcsv

In my case the source file has windows-1250 encoding and iconv prints tons of notices about illegal characters in input string...

So this solution helped me a lot:

/**
 * getting CSV array with UTF-8 encoding
 *
 * @param   resource    &$handle
 * @param   integer     $length
 * @param   string      $separator
 *
 * @return  array|false
 */
private function fgetcsvUTF8(&$handle, $length, $separator = ';')
{
    if (($buffer = fgets($handle, $length)) !== false)
    {
        $buffer = $this->autoUTF($buffer);
        return str_getcsv($buffer, $separator);
    }
    return false;
}

/**
 * automatic convertion windows-1250 and iso-8859-2 info utf-8 string
 *
 * @param   string  $s
 *
 * @return  string
 */
private function autoUTF($s)
{
    // detect UTF-8
    if (preg_match('#[\x80-\x{1FF}\x{2000}-\x{3FFF}]#u', $s))
        return $s;

    // detect WINDOWS-1250
    if (preg_match('#[\x7F-\x9F\xBC]#', $s))
        return iconv('WINDOWS-1250', 'UTF-8', $s);

    // assume ISO-8859-2
    return iconv('ISO-8859-2', 'UTF-8', $s);
}

Response to @manvel's answer - use str_getcsv instead of explode - because of cases like this:

some;nice;value;"and;here;comes;combinated;value";and;some;others

explode will explode string into parts:

some
nice
value
"and
here
comes
combinated
value"
and
some
others

but str_getcsv will explode string into parts:

some
nice
value
and;here;comes;combinated;value
and
some
others

Timeout jQuery effects

You can do something like this:

$('.notice')
    .fadeIn()
    .animate({opacity: '+=0'}, 2000)   // Does nothing for 2000ms
    .fadeOut('fast');

Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.

git checkout all the files

  • If you are in base directory location of your tracked files then git checkout . will works otherwise it won't work

Oracle SQL - select within a select (on the same table!)

This is precisely the sort of scenario where analytics come to the rescue.

Given this test data:

SQL> select * from employment_history
  2  order by Gc_Staff_Number
  3             , start_date
  4  /

GC_STAFF_NUMBER START_DAT END_DATE  C
--------------- --------- --------- -
           1111 16-OCT-09           Y
           2222 08-MAR-08 26-MAY-09 N
           2222 12-DEC-09           Y
           3333 18-MAR-07 08-MAR-08 N
           3333 01-JUL-09 21-MAR-09 N
           3333 30-JUL-10           Y

6 rows selected.

SQL> 

An inline view with an analytic LAG() function provides the right answer:

SQL> select Gc_Staff_Number
  2             , start_date
  3             , prev_end_date
  4  from   (
  5      select Gc_Staff_Number
  6             , start_date
  7             , lag (end_date) over (partition by Gc_Staff_Number
  8                                    order by start_date )
  9                  as prev_end_date
 10             , current_flag
 11      from employment_history
 12  )
 13  where current_flag = 'Y'
 14  /

GC_STAFF_NUMBER START_DAT PREV_END_
--------------- --------- ---------
           1111 16-OCT-09
           2222 12-DEC-09 26-MAY-09
           3333 30-JUL-10 21-MAR-09

SQL>

The inline view is crucial to getting the right result. Otherwise the filter on CURRENT_FLAG removes the previous rows.

How to grant remote access to MySQL for a whole subnet?

MySQL 8.0.23 onwards now support CIDR notation also.

So, basically:

-- CIDR Notation
GRANT ... TO 'user'@'192.168.1.0/24' IDENTIFIED BY ...

-- Netmask Notation
GRANT ... TO 'user'@'192.168.1.0/255.255.255.0' IDENTIFIED BY ...

Eclipse - java.lang.ClassNotFoundException

JUnit 4.4 is not supported by the JMockit/JUnit integration. Only versions 4.5 or newer are supported that.

read word by word from file in C++

what you are doing here is reading one character at a time from the input stream and assume that all the characters between " " represent a word. BUT it's unlikely to be a " " after the last word, so that's probably why it does not work:

"word1 word2 word2EOF"

Why in C++ do we use DWORD rather than unsigned int?

For myself, I would assume unsigned int is platform specific. Integer could be 8 bits, 16 bits, 32 bits or even 64 bits.

DWORD in the other hand, specifies its own size, which is Double Word. Word are 16 bits so DWORD will be known as 32 bit across all platform

How can I group by date time column without taking time into consideration

Cast/Convert the values to a Date type for your group by.

GROUP BY CAST(myDateTime AS DATE)

Find the item with maximum occurrences in a list

may something like this:

testList = [1, 2, 3, 4, 2, 2, 1, 4, 4] print(max(set(testList), key = testList.count))

Disable spell-checking on HTML textfields

An IFrame WILL "trigger" the spell checker (if it has content-editable set to true) just as a textfield, at least in Chrome.

How can I write output from a unit test?

Are you sure you're running your unit tests in Debug? Debug.WriteLine won't be called in Release builds.

Two options to try are:

  • Trace.WriteLine(), which is built into release builds as well as debug

  • Undefine DEBUG in your build settings for the unit test

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

getOutputStream() has already been called for this response

I got the same error by using response.getWriter() before a request.getRequestDispatcher(path).forward(request, response);. So start works fine when I replace it by response.getOutputStream()

What's the difference between xsd:include and xsd:import?

Direct quote from MSDN: <xsd:import> Element, Remarks section

The difference between the include element and the import element is that import element allows references to schema components from schema documents with different target namespaces and the include element adds the schema components from other schema documents that have the same target namespace (or no specified target namespace) to the containing schema. In short, the import element allows you to use schema components from any schema; the include element allows you to add all the components of an included schema to the containing schema.

How can I force division to be floating point? Division keeps rounding down to 0?

In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a

from __future__ import division

at the top of your module.

A process crashed in windows .. Crash dump location

a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).

If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP

Inline onclick JavaScript variable

<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>

How do I use a delimiter with Scanner.useDelimiter in Java?

For example:

String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);

This will let you use Enter as a delimiter.

Thus, if you input:

Hello world (ENTER)

it will print 'Hello World'.

How can I use JSON data to populate the options of a select box?

You should do it like this:

function getResults(str) {
  $.ajax({
        url:'suggest.html',
        type:'POST',
        data: 'q=' + str,
        dataType: 'json',
        success: function( json ) {
           $.each(json, function(i, optionHtml){
              $('#myselect').append(optionHtml);
           });
        }
    });
};

Cheers

How can I set the default value for an HTML <select> element?

An improvement for nobita's answer. Also you can improve the visual view of the drop down list, by hiding the element 'Choose here'.

_x000D_
_x000D_
<select>_x000D_
  <option selected disabled hidden>Choose here</option>_x000D_
  <option value="1">One</option>_x000D_
  <option value="2">Two</option>_x000D_
  <option value="3">Three</option>_x000D_
  <option value="4">Four</option>_x000D_
  <option value="5">Five</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to check if a string array contains one string in JavaScript?

var stringArray = ["String1", "String2", "String3"];

return (stringArray.indexOf(searchStr) > -1)

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

Failed to execute removeChild on Node

I was wraped it with <> </> as a parent when I changed it to normal , div , its worked fine

Including all the jars in a directory within the Java classpath

Please note that wildcard expansion is broken for Java 7 on Windows.

Check out this StackOverflow issue for more information.

The workaround is to put a semicolon right after the wildcard. java -cp "somewhere/*;"

Remove the last chars of the Java String variable

Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.

phpmailer - The following SMTP Error: Data not accepted

In my case the problem was with the content of mail. When I changed content to simpler content without HTML, it worked. But after updating the phpmailer everything solved.

What's the difference between KeyDown and KeyPress in .NET?

KEYUP will be captured only once, upon release of the key pressed, regardless of how long will the key be held down, so if you want to capture such press only once, KEYUP is the suitable event to capture.

Java: How to convert a File object to a String object in java?

I use apache common IO to read a text file into a single string

String str = FileUtils.readFileToString(file);

simple and "clean". you can even set encoding of the text file with no hassle.

String str = FileUtils.readFileToString(file, "UTF-8");

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

In my case, Server had lower version framework than your application. installed latest version framework and it fixed this issue.

How to detect Adblock on my website?

My advice is: don't do it!

Any scenario where you treat people as "wrongdoers" is going to result in them fighting back.

Here's my proposal.

Put a small unobtrusive message at the top of the page (regardless of whether ads are being blocked) with the text I *totally* respect your right to block ads and a link to another page/pop-up entitled Read more ....

On the other page, make it clear that you understand it's their computer and they are free to use ad blocking.

Also make it clear in a non-accusatory way that the use of these blockers makes it more difficult for you to deliver great content (explaining why in detail) and that, while you'd prefer the ad blocking to not happen on your site, it's totally their decision. Focus on the positives of turning off blocking.

Those who are vehemently opposed to ads will ignore this but you never stood a chance of convincing them anyway. Those who are indifferent may well be swayed by your appeal since you're not doing the whole "let me get my way or I'll take my ball and go home" thing that honestly should be the exclusive domain of five year old children.

Remember, no-one held a gun to your head and forced you to put your stuff on the net. Treat your readership/users with respect and you'll probably find a good number of them will reciprocate.

Entity Framework : How do you refresh the model when the db changes?

I've been working on a project, not too large, that incorporates Entity Framework, about a dozen tables, and about 15 stored procs and functions. After weeks of development, attempting to refresh my tables and stored procs has yielded mixed results as far as successfully updating the model. Sometimes the changes are effective, most times they are not. Simple column changes (changing order, adding, removing, or renaming) sometimes works, most times does not. Visual Studio seems to have more problems with refreshing than just adding new. It also exhibits more problems with stored proc changes not being reflected, especially when columns are added or deleted or renamed. I have not detected any consistent behavior so i can't say "This type of change will always be updated and this type of change will not".

End result, if you want 100% effective solution, delete the EDMX file from the project, "Add new" item to project (ADO.NET Entity Data Model), and make sure you use the same name for the Model Name. This works every time.

How can I generate Unix timestamps?

In python add the following lines to get a time stamp:

>>> import time
>>> time.time()
1335906993.995389
>>> int(time.time())
1335906993

Delete all rows in an HTML table

this is a simple code I just wrote to solve this, without removing the header row (first one).

var Tbl = document.getElementById('tblId');
while(Tbl.childNodes.length>2){Tbl.removeChild(Tbl.lastChild);}

Hope it works for you!!.

Why can't non-default arguments follow default arguments?

Let me clear two points here :

  • firstly non-default argument should not follow default argument , it means you can't define (a=b,c) in function the order of defining parameter in function are :
    • positional parameter or non-default parameter i.e (a,b,c)
    • keyword parameter or default parameter i.e (a="b",r="j")
    • keyword-only parameter i.e (*args)
    • var-keyword parameter i.e (**kwargs)

def example(a, b, c=None, r="w" , d=[], *ae, **ab):

(a,b) are positional parameter

(c=none) is optional parameter

(r="w") is keyword parameter

(d=[]) is list parameter

(*ae) is keyword-only

(**ab) is var-keyword parameter

  • now secondary thing is if i try something like this : def example(a, b, c=a,d=b):

argument is not defined when default values are saved,Python computes and saves default values when you define the function

c and d are not defined, does not exist, when this happens (it exists only when the function is executed)

"a,a=b" its not allowed in parameter.

Better way to find last used row

I use this routine to find the count of data rows. There is a minimum of overhead required, but by counting using a decreasing scale, even a very large result requires few iterations. For example, a result of 28,395 would only require 2 + 8 + 3 + 9 + 5, or 27 times through the loop, instead of a time-expensive 28,395 times.

Even were we to multiply that by 10 (283,950), the iteration count is the same 27 times.

Dim lWorksheetRecordCountScaler as Long
Dim lWorksheetRecordCount as Long

Const sDataColumn = "A"   '<----Set to column that has data in all rows (Code, ID, etc.)

    'Count the data records
    lWorksheetRecordCountScaler = 100000  'Begin by counting in 100,000-record bites
    lWorksheetRecordCount = lWorksheetRecordCountScaler

    While lWorksheetRecordCountScaler >= 1

        While Sheets("Sheet2").Range(sDataColumn & lWorksheetRecordCount + 2).Formula > " "
            lWorksheetRecordCount = lWorksheetRecordCount + lWorksheetRecordCountScaler
        Wend

        'To the beginning of the previous bite, count 1/10th of the scale from there
        lWorksheetRecordCount = lWorksheetRecordCount - lWorksheetRecordCountScaler
        lWorksheetRecordCountScaler = lWorksheetRecordCountScaler / 10

    Wend

    lWorksheetRecordCount = lWorksheetRecordCount + 1   'Final answer

What is sys.maxint in Python 3?

Python 3 ints do not have a maximum.

If your purpose is to determine the maximum size of an int in C when compiled the same way Python was, you can use the struct module to find out:

>>> import struct
>>> platform_c_maxint = 2 ** (struct.Struct('i').size * 8 - 1) - 1

If you are curious about the internal implementation details of Python 3 int objects, Look at sys.int_info for bits per digit and digit size details. No normal program should care about these.

How to fix warning from date() in PHP"

You need to set the default timezone smth like this :

date_default_timezone_set('Europe/Bucharest');

More info about this in http://php.net/manual/en/function.date-default-timezone-set.php

Or you could use @ in front of date to suppress the warning however as the warning states it's not safe to rely on the servers default timezone

What is a typedef enum in Objective-C?

Apple recommends defining enums like this since Xcode 4.4:

typedef enum ShapeType : NSUInteger {
    kCircle,
    kRectangle,
    kOblateSpheroid
} ShapeType;

They also provide a handy macro NS_ENUM:

typedef NS_ENUM(NSUInteger, ShapeType) {
    kCircle,
    kRectangle,
    kOblateSpheroid
};

These definitions provide stronger type checking and better code completion. I could not find official documentation of NS_ENUM, but you can watch the "Modern Objective-C" video from WWDC 2012 session here.


UPDATE
Link to official documentation here.

SQL Case Sensitive String Compare

Select * from a_table where attribute = 'k' COLLATE Latin1_General_CS_AS 

Did the trick.

Variable used in lambda expression should be final or effectively final

A variable used in lambda expression should be a final or effectively final, but you can assign a value to a final one element array.

private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone calTz) {
    try {
        TimeZone calTzLocal[] = new TimeZone[1];
        calTzLocal[0] = calTz;
        cal.getComponents().get("VTIMEZONE").forEach(component -> {
            TimeZone v = component;
            v.getTimeZoneId();
            if (calTzLocal[0] == null) {
                calTzLocal[0] = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
            }
        });
    } catch (Exception e) {
        log.warn("Unable to determine ical timezone", e);
    }
    return null;
}

How to run batch file from network share without "UNC path are not supported" message?

My situation is just a little different. I'm running a batch file on startup to distribute the latest version of internal business applications.

In this situation I'm using the Windows Registry Run Key with the following string

cmd /c copy \\serverName\SharedFolder\startup7.bat %USERPROFILE% & %USERPROFILE%\startup7.bat

This runs two commands on startup in the correct sequence. First copying the batch file locally to a directory the user has permission to. Then executing the same batch file. I can create a local directory c:\InternalApps and copy all of the files from the network.

This is probably too late to solve the original poster's question but it may help someone else.

Get bytes from std::string in C++

From a std::string you can use the c_ptr() method if you want to get at the char_t buffer pointer.

It looks like you just want copy the characters of the string into a new buffer. I would simply use the std::string::copy function:

length = str.copy( buffer, str.size() );

How are booleans formatted in Strings in Python?

If you want True False use:

"%s %s" % (True, False)

because str(True) is 'True' and str(False) is 'False'.

or if you want 1 0 use:

"%i %i" % (True, False)

because int(True) is 1 and int(False) is 0.

Jquery show/hide table rows

http://sandbox.phpcode.eu/g/corrected-b5fe953c76d4b82f7e63f1cef1bc506e.php

<span id="black_only">Show only black</span><br>
<span id="white_only">Show only white</span><br>
<span id="all">Show all of them</span>
<style>
.black{background-color:black;}
#white{background-color:white;}
</style>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
  <tr class="black">
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
  </tr>
</thead>
<tbody>
  <tr id="white">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
  <tr class="black" style="background-color:black;">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
</tbody>
<script>
$(function(){
   $("#black_only").click(function(){
    $("#white").hide();
    $(".black").show();

   });
   $("#white_only").click(function(){
    $(".black").hide();
    $("#white").show();

   });
   $("#all").click(function(){
    $("#white").show();
    $(".black").show();

   });

});
</script>

Android ListView with onClick items

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent i = new Intent(getActivity(), DiscussAddValu.class);
        startActivity(i);
    }
});

How to show live preview in a small popup of linked page on mouse over on link?

Another way is to use a website thumbnail/link preview service LinkPeek (even happens to show a screenshot of StackOverflow as a demo right now), URL2PNG, Browshot, Websnapr, or an alternative.

I can’t find the Android keytool

Okay, so this post is from six months ago, but I thought I would add some info here for people who are confused about the whole API key/MD5 fingerprint business. It took me a while to figure out, so I assume others have had trouble with it too (unless I'm just that dull).

These directions are for Windows XP, but I imagine it is similar for other versions of Windows. It appears Mac and Linux users have an easier time with this so I won't address them.

So in order to use mapviews in your Android apps, Google wants to check in with them so you can sign off on an Android Maps APIs Terms Of Service agreement. I think they don't want you to make any turn-by-turn GPS apps to compete with theirs or something. I didn't really read it. Oops.

So go to http://code.google.com/android/maps-api-signup.html and check it out. They want you to check the "I have read and agree with the terms and conditions" box and enter your certificate's MD5 fingerprint. Wtf is that, you might say. I don't know, but just do what I say and your Android app doesn't get hurt.

Go to Start>Run and type cmd to open up a command prompt. You need to navigate to the directory with the keytool.exe file, which might be in a slightly different place depending on which version JDK you have installed. Mine is in C:\Program Files\Java\jdk1.6.0_21\bin but try browsing to the Java folder and see what version you have and change the path accordingly.

After navigating to C:\Program Files\Java\<"your JDK version here">\bin in the command prompt, type

keytool -list -keystore "C:/Documents and Settings/<"your user name here">/.android/debug.keystore"

with the quotes. Of course <"your user name here"> would be your own Windows username.

(If you are having trouble finding this path and you are using Eclipse, you can check Window>preferences>Android>Build and check out the "Default Debug keystore")

Press enter and it will prompt you for a password. Just press enter. And voila, at the bottom is your MD5 fingerprint. Type your fingerprint into the text box at the Android Maps API Signup page and hit Generate API Key.

And there's your key in all its glory, with a handy sample xml layout with your key entered for you to copy and paste.

The Role Manager feature has not been enabled

You can do this by reading from the boolean property at:

System.Web.Security.Roles.Enabled

This is a direct read from the enabled attribute of the roleManager element in the web.config:

<configuration>
  <system.web>
    <roleManager enabled="true" />
  </system.web>
</configuration>


Update:
For more information, check out this MSDN sample: https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110).aspx

how to have two headings on the same line in html

Add a span with the style="float: right" element inside the h1 element. So you can add a "goto top of the page" link, with a unicode arrow link button.

<h1 id="myAnchor">Headline Text
<span style="float: right"><a href="#top" aria-hidden="true">?</a></span>
</h1>

How to "select distinct" across multiple data frame columns in pandas?

You can use the drop_duplicates method to get the unique rows in a DataFrame:

In [29]: df = pd.DataFrame({'a':[1,2,1,2], 'b':[3,4,3,5]})

In [30]: df
Out[30]:
   a  b
0  1  3
1  2  4
2  1  3
3  2  5

In [32]: df.drop_duplicates()
Out[32]:
   a  b
0  1  3
1  2  4
3  2  5

You can also provide the subset keyword argument if you only want to use certain columns to determine uniqueness. See the docstring.

Removing Duplicate Values from ArrayList

     public List<Contact> removeDuplicates(List<Contact> list) {
    // Set set1 = new LinkedHashSet(list);
    Set set = new TreeSet(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
                 if(((Contact)o1).getId().equalsIgnoreCase(((Contact)2).getId()) ) {
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);
    final List newList = new ArrayList(set);
    return newList;
}

How do you compare two version Strings in Java?

public int compare(String v1, String v2) {
        v1 = v1.replaceAll("\\s", "");
        v2 = v2.replaceAll("\\s", "");
        String[] a1 = v1.split("\\.");
        String[] a2 = v2.split("\\.");
        List<String> l1 = Arrays.asList(a1);
        List<String> l2 = Arrays.asList(a2);


        int i=0;
        while(true){
            Double d1 = null;
            Double d2 = null;

            try{
                d1 = Double.parseDouble(l1.get(i));
            }catch(IndexOutOfBoundsException e){
            }

            try{
                d2 = Double.parseDouble(l2.get(i));
            }catch(IndexOutOfBoundsException e){
            }

            if (d1 != null && d2 != null) {
                if (d1.doubleValue() > d2.doubleValue()) {
                    return 1;
                } else if (d1.doubleValue() < d2.doubleValue()) {
                    return -1;
                }
            } else if (d2 == null && d1 != null) {
                if (d1.doubleValue() > 0) {
                    return 1;
                }
            } else if (d1 == null && d2 != null) {
                if (d2.doubleValue() > 0) {
                    return -1;
                }
            } else {
                break;
            }
            i++;
        }
        return 0;
    }

What is an NP-complete in computer science?

NP-complete problems are a set of problems to each of which any other NP-problem can be reduced in polynomial time, and whose solution may still be verified in polynomial time. That is, any NP problem can be transformed into any of the NP-complete problems. – Informally, an NP-complete problem is an NP problem that is at least as "tough" as any other problem in NP.

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

With Worksheets("Cable Cards")
    .Range(.Cells(RangeStartRow, RangeStartColumn), _
           .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

Similarly, fully qualify all your Cells object.

How to Identify port number of SQL server

PowerShell solution that shows all of the instances on the host as well as their incoming traffic addresses. The second bit might be helpful if all you know is the DNS:

ForEach ($SQL_Proc in Get-Process | Select-Object -Property ProcessName, Id | Where-Object {$_.ProcessName -like "*SQL*"})
{
    Get-NetTCPConnection | `
     Where-Object {$_.OwningProcess -eq $SQL_Proc.id} | `
      Select-Object -Property `
                                @{Label ="Process_Name";e={$SQL_Proc.ProcessName}}, `
                                @{Label ="Local_Address";e={$_.LocalAddress + ":" + $_.LocalPort }},  `
                                @{Label ="Remote_Address";e={$_.RemoteAddress + ":" + $_.RemotePort}}, State | `
      Format-Table
} 

ImportError: No module named mysql.connector using Python2

What worked for me was to download the .deb file directly and install it (dpkg -i mysql-connector-python_2.1.7-1ubuntu16.04_all.deb). Python downloads are located here (you will need to create a free MySQL login to download first). Make sure you choose the correct version, i.e. (python_2.1.7 vs. python-py3_2.1.7). Only the "Architecture Independent" version worked for me.

Get real path from URI, Android KitKat new storage access framework

This answer is based on your somewhat vague description. I assume that you fired an intent with action: Intent.ACTION_GET_CONTENT

And now you get content://com.android.providers.media.documents/document/image:62 back instead of the previously media provider URI, correct?

On Android 4.4 (KitKat) the new DocumentsActivity gets opened when an Intent.ACTION_GET_CONTENT is fired thus leading to grid view (or list view) where you can pick an image, this will return the following URIs to calling context (example): content://com.android.providers.media.documents/document/image:62 (these are the URIs to the new document provider, it abstracts away the underlying data by providing generic document provider URIs to clients).

You can however access both gallery and other activities responding to Intent.ACTION_GET_CONTENT by using the drawer in the DocumentsActivity (drag from left to right and you'll see a drawer UI with Gallery to choose from). Just as pre KitKat.

If you still which to pick in DocumentsActivity class and need the file URI, you should be able to do the following (warning this is hacky!) query (with contentresolver):content://com.android.providers.media.documents/document/image:62 URI and read the _display_name value from the cursor. This is somewhat unique name (just the filename on local files) and use that in a selection (when querying) to mediaprovider to get the correct row corresponding to this selection from here you can fetch the file URI as well.

The recommended ways of accessing document provider can be found here (get an inputstream or file descriptor to read file/bitmap):

Examples of using documentprovider

How to start automatic download of a file in Internet Explorer?

Back to the roots, i use this:

<meta http-equiv="refresh" content="0; url=YOURFILEURL"/>

Maybe not WC3 conform but works perfect on all browsers, no HTML5/JQUERY/Javascript.

Greetings Tom :)

TimePicker Dialog from clicking EditText

I dont know if this will work for you, it works for me just fine.

Create a method for the Date/Time picker dialog.

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is called, below method will be called.
    // The arguments will be working to get the Day of Week to show it in a special TextView for it.

    public void onDateSet(DatePicker view, int selectedYear,
                          int selectedMonth, int selectedDay) {
        String year1 = String.valueOf(selectedYear);
        String month1 = String.valueOf(selectedMonth + 1);
        String day1 = String.valueOf(selectedDay);
        delivDate.setText(month1 + "/" + day1 + "/" + year1);
        delivDay.setText(DateFormat.format("EEEE", new Date(selectedYear, selectedMonth, selectedDay - 1)).toString());
    }
};

and then, wherever you want you can do it just like this

public void setDateOnClick (View view) {
    Calendar cal = Calendar.getInstance();

    DatePickerDialog datePicker = new DatePickerDialog(this, datePickerListener,
            cal.get(Calendar.YEAR),
            cal.get(Calendar.MONTH),
            cal.get(Calendar.DAY_OF_MONTH));
    //Create a cancel button and set the title of the dialog.
    datePicker.setCancelable(false);
    datePicker.setTitle("Select the date");
    datePicker.show();
}

hope you find this as your solution.

Difference between attr_accessor and attr_accessible

A quick & concise difference overview :

attr_accessor is an easy way to create read and write accessors in your class. It is used when you do not have a column in your database, but still want to show a field in your forms. This field is a “virtual attribute” in a Rails model.

virtual attribute – an attribute not corresponding to a column in the database.

attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

Google throws this exception on Activity's onCreate method after v27, their meaning is : if an Activity is translucent or floating, its orientation should be relied on parent(background) Activity, can't make decision on itself.

Even if you remove android:screenOrientation="portrait" from the floating or translucent Activity but fix orientation on its parent(background) Activity, it is still fixed by the parent, I have tested already.

One special situation : if you make translucent on a launcher Activity, it has't parent(background), so always rotate with device. Want to fix it, you have to take another way to replace <item name="android:windowIsTranslucent">true</item> style.

What is the most accurate way to retrieve a user's correct IP address in PHP?

I do wonder if perhaps you should iterate over the exploded HTTP_X_FORWARDED_FOR in reverse order, since my experience has been that the user's IP address ends up at the end of the comma-separated list, so starting at the start of the header, you're more likely to get the ip address of one of the proxies returned, which could potentially still allow session hijacking as many users may come through that proxy.

Detect click outside element

Can be solved nicely by setting up a custom directive once:

Vue.directive('click-outside', {
  bind () {
      this.event = event => this.vm.$emit(this.expression, event)
      this.el.addEventListener('click', this.stopProp)
      document.body.addEventListener('click', this.event)
  },   
  unbind() {
    this.el.removeEventListener('click', this.stopProp)
    document.body.removeEventListener('click', this.event)
  },

  stopProp(event) { event.stopPropagation() }
})

Usage:

<div v-click-outside="nameOfCustomEventToCall">
  Some content
</div>

In the component:

events: {
  nameOfCustomEventToCall: function (event) {
    // do something - probably hide the dropdown menu / modal etc.
  }
}

Working Demo on JSFiddle with additional info about caveats:

https://jsfiddle.net/Linusborg/yzm8t8jq/

Dynamic creation of table with DOM

var html = "";
    for (var i = 0; i < data.length; i++){
    html +="<tr>"+
            "<td>"+ (i+1) + "</td>"+
            "<td>"+ data[i].name + "</td>"+
            "<td>"+ data[i].number + "</td>"+
            "<td>"+ data[i].city + "</td>"+
            "<td>"+ data[i].hobby + "</td>"+
            "<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);

How do I create an executable in Visual Studio 2013 w/ C++?

Just click on "Build" on the top menu and then click on "Publish ".... Then a pop up will open and there u can define the folder which u want to save the .exe file and by clicking "Next" will allow u to set up the advanced settings... DONE!

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

In addition to the native versions, but you may want to try BitNami MAMP Stacks (disclaimer, I am one of the developers). They are completely free, all-in-one bundles of Apache, MySQL, PHP and a several other third-party libraries and utilities that are useful when developing locally. In particular, they are completely self-contained so you can have several one installed at the same time, with different versions of Apache and MySQL and they will not interfere with each other. You can get them from http://bitnami.org/stack/mampstack or directly from the Mac OS X app store https://itunes.apple.com/app/mamp-stack/id571310406

How do I ALTER a PostgreSQL table and make a column unique?

I figured it out from the PostgreSQL docs, the exact syntax is:

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

How to copy files from 'assets' folder to sdcard?

Based on your solution, I did something of my own to allow subfolders. Someone might find this helpful:

...

copyFileOrDir("myrootdir");

...

private void copyFileOrDir(String path) {
    AssetManager assetManager = this.getAssets();
    String assets[] = null;
    try {
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(path);
        } else {
            String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
            File dir = new File(fullPath);
            if (!dir.exists())
                dir.mkdir();
            for (int i = 0; i < assets.length; ++i) {
                copyFileOrDir(path + "/" + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}

private void copyFile(String filename) {
    AssetManager assetManager = this.getAssets();

    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open(filename);
        String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
        out = new FileOutputStream(newFileName);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }

}

Phone Number Validation MVC

You don't have a validator on the page. Add something like this to show the validation message.

@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })

Get all child views inside LinearLayout at once

Get all views of a view plus its children recursively in Kotlin:

private fun View.getAllViews(): List<View> {
    if (this !is ViewGroup || childCount == 0) return listOf(this)

    return children
            .toList()
            .flatMap { it.getAllViews() }
            .plus(this as View)
}

convert HTML ( having Javascript ) to PDF using JavaScript

I'm surprised no one mentioned the possibility to use an API to do the work.

Granted, if you want to stay secure, converting HTML to PDF directly from within the browser using javascript is not a good idea.

But here's what you can do:

When your user hit the "Print" (for example) button, you:

  1. Send a request to your server at a specific endpoint with details about what to convert (URL of the page for instance).
  2. This endpoint will then send the data to convert to an API, and will receive the PDF in response
  3. which it will return to your user.

For a user point of view, they will receive a PDF by clicking on a button.

There are many available API that does the job, some better than others (that's not why I'm here) and a Google search will give you a lot of answers.

Depending on what is written your backend, you might be interested in PDFShift (Truth: I work there).

They offer ready to work packages for PHP, Python and Node.js. All you have to do is install the package, create an account, indicate your API key and you are all set!

The advantage of the API is that they work well in all languages. All you have to do is a request (generally POST) containing the data you want to be converted and get a PDF back. And depending on your usage, it's generally free, except if you are a heavy user.

Convert an object to an XML string

    public static string Serialize(object dataToSerialize)
    {
        if(dataToSerialize==null) return null;

        using (StringWriter stringwriter = new System.IO.StringWriter())
        {
            var serializer = new XmlSerializer(dataToSerialize.GetType());
            serializer.Serialize(stringwriter, dataToSerialize);
            return stringwriter.ToString();
        }
    }

    public static T Deserialize<T>(string xmlText)
    {
        if(String.IsNullOrWhiteSpace(xmlText)) return default(T);

        using (StringReader stringReader = new System.IO.StringReader(xmlText))
        {
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
    }

Converting Python dict to kwargs?

Use the double-star (aka double-splat?) operator:

func(**{'type':'Event'})

is equivalent to

func(type='Event')

What does "publicPath" in Webpack do?

the publicPath is just used for dev purpose, I was confused at first time I saw this config property, but it makes sense now that I've used webpack for a while

suppose you put all your js source file under src folder, and you config your webpack to build the source file to dist folder with output.path.

But you want to serve your static assets under a more meaningful location like webroot/public/assets, this time you can use out.publicPath='/webroot/public/assets', so that in your html, you can reference your js with <script src="/webroot/public/assets/bundle.js"></script>.

when you request webroot/public/assets/bundle.js the webpack-dev-server will find the js under the dist folder

Update:

thanks for Charlie Martin to correct my answer

original: the publicPath is just used for dev purpose, this is not just for dev purpose

No, this option is useful in the dev server, but its intention is for asynchronously loading script bundles in production. Say you have a very large single page application (for example Facebook). Facebook wouldn't want to serve all of its javascript every time you load the homepage, so it serves only whats needed on the homepage. Then, when you go to your profile, it loads some more javascript for that page with ajax. This option tells it where on your server to load that bundle from

Set up Python simpleHTTPserver on Windows

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

The following works for me:

python -m http.server [<portNo>]

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

How do I give ASP.NET permission to write to a folder in Windows 7?

My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...

@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.

Can you delete multiple branches in one command with Git?

If you want to delete multiple branches for cleanup this will work

 git branch -d branch1 branch2 branch3

also if you want to reflect the deletion action to remote you can use this to push them

 git push origin --delete branch1 branch2 branch3

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

The way I got around this issue is by not calling intent within a dialog. **** use syntax applicable to activity or fragment accordingly

@Override
public void onClick(DialogInterface dialog, int which) {
    checkvariable= true;
    getActivity().finish();
}

@Override
public void onStop() {
    super.onStop();
    if (checkvariable) {
        startActivity(intent); 
    }
}

Single TextView with multiple colored text

25 June 2020 by @canerkaseler

I would like to share Kotlin Answer :

fun setTextColor(tv:TextView, startPosition:Int, endPosition:Int, color:Int){
    val spannableStr = SpannableString(tv.text)

    val underlineSpan = UnderlineSpan()
    spannableStr.setSpan(
        underlineSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val backgroundColorSpan = ForegroundColorSpan(this.resources.getColor(R.color.agreement_color))
    spannableStr.setSpan(
        backgroundColorSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val styleSpanItalic = StyleSpan(Typeface.BOLD)
    spannableStr.setSpan(
        styleSpanItalic,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    tv.text = spannableStr
}

After, call above function. You can call more than one:

setTextColor(textView, 0, 61, R.color.agreement_color)
setTextColor(textView, 65, 75, R.color.colorPrimary)

Output: You can see underline and different colors with each other.

@canerkaseler

How to write a foreach in SQL Server?

The following line is wrong in your version:

WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))

(Missing the @)

Might be an idea to change your naming convention so that the tables are more different.

Remove new lines from string and replace with one empty space

Many of these solutions didn't work for me. This did the trick though:-

$svgxml = preg_replace("/(*BSR_ANYCRLF)\R/",'',$svgxml);

Here is the reference:- PCRE and New Lines

How to send a simple email from a Windows batch file?

If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.

I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.

A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.

Android Layout Right Align

You can do all that by using just one RelativeLayout (which, btw, don't need android:orientation parameter). So, instead of having a LinearLayout, containing a bunch of stuff, you can do something like:

<RelativeLayout>
    <ImageButton
        android:layout_width="wrap_content"
        android:id="@+id/the_first_one"
        android:layout_alignParentLeft="true"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_toRightOf="@+id/the_first_one"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

As you noticed, there are some XML parameters missing. I was just showing the basic parameters you had to put. You can complete the rest.

preg_match in JavaScript?

JavaScript has a RegExp object which does what you want. The String object has a match() function that will help you out.

var matches = text.match(/price\[(\d+)\]\[(\d+)\]/);
var productId = matches[1];
var shopId    = matches[2];

How to concatenate int values in java?

If you multiply b by 1000, you will not lose any of the values. See below for the math.

10000
    0
  200
   20
    1
=====
10221

What is the 'realtime' process priority setting for?

A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system. As such a CPU bound realtime priority thread can totally ruin a machine.

Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.

For Vista and beyond, one option for applications that do require that they run at realtime priorities is to use the Multimedia Class Scheduler Service (MMCSS) and let it manage your threads priority. The MMCSS will prevent your application from using too much CPU time so you don't have to worry about tanking the machine.

jQuery: How to capture the TAB keypress within a Textbox

This worked for me:

$("[id*=txtName]").on('keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); alert('Tab Pressed'); } });

How to import NumPy in the Python shell

On Debian/Ubuntu:

aptitude install python-numpy

On Windows, download the installer:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems, download the tar.gz and run the following:

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

How to find files that match a wildcard string in Java?

Util Method:

public static boolean isFileMatchTargetFilePattern(final File f, final String targetPattern) {
        String regex = targetPattern.replace(".", "\\.");  //escape the dot first
        regex = regex.replace("?", ".?").replace("*", ".*");
        return f.getName().matches(regex);

    }

jUnit Test:

@Test
public void testIsFileMatchTargetFilePattern()  {
    String dir = "D:\\repository\\org\my\\modules\\mobile\\mobile-web\\b1605.0.1";
    String[] regexPatterns = new String[] {"_*.repositories", "*.pom", "*-b1605.0.1*","*-b1605.0.1", "mobile*"};
    File fDir = new File(dir);
    File[] files = fDir.listFiles();

    for (String regexPattern : regexPatterns) {
        System.out.println("match pattern [" + regexPattern + "]:");
        for (File file : files) {
            System.out.println("\t" + file.getName() + " matches:" + FileUtils.isFileMatchTargetFilePattern(file, regexPattern));
        }
    }
}

Output:

match pattern [_*.repositories]:
    mobile-web-b1605.0.1.pom matches:false
    mobile-web-b1605.0.1.war matches:false
    _remote.repositories matches:true
match pattern [*.pom]:
    mobile-web-b1605.0.1.pom matches:true
    mobile-web-b1605.0.1.war matches:false
    _remote.repositories matches:false
match pattern [*-b1605.0.1*]:
    mobile-web-b1605.0.1.pom matches:true
    mobile-web-b1605.0.1.war matches:true
    _remote.repositories matches:false
match pattern [*-b1605.0.1]:
    mobile-web-b1605.0.1.pom matches:false
    mobile-web-b1605.0.1.war matches:false
    _remote.repositories matches:false
match pattern [mobile*]:
    mobile-web-b1605.0.1.pom matches:true
    mobile-web-b1605.0.1.war matches:true
    _remote.repositories matches:false

Mockito - difference between doReturn() and when()

Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...

PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));

So it will return false when the method is called in same test case and then it will return false again and lastly true.

Calculating time difference between 2 dates in minutes

ROUND(time_to_sec((TIMEDIFF(NOW(), "2015-06-10 20:15:00"))) / 60);

How to get your Netbeans project into Eclipse

In Eclipse:

File>Import>General>Existing projects in Workspace

Browse until get the netbeans project folder > Finish

Bootstrap - 5 column layout

Here is another simple way of doing this, by adding width 20% to every col-xs-2:

<div class="col-xs-12">
     <div class="col-xs-2" style="width:20%;" id="p1">One</div>
     <div class="col-xs-2" style="width:20%;" id="p2">Two</div>
     <div class="col-xs-2" style="width:20%;" id="p3">Three</div>
     <div class="col-xs-2" style="width:20%;" id="p4">Four</div>
     <div class="col-xs-2" style="width:20%;" id="p5">Five</div>
</div>

How to make child divs always fit inside parent div?

I think I have the solution to your question, assuming you can use flexbox in your project. What you want to do is make #one a flexbox using display: flex and use flex-direction: column to make it a column alignment.

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.border {_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.margin {_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
#one {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
#two {_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
#three {_x000D_
  width: 100px;_x000D_
  height: 100%;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="one" class="border">_x000D_
    <div id="two" class="border margin"></div>_x000D_
    <div id="three" class="border margin"></div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I install cURL on cygwin?

If someone is having problem with finding CURL in the list in setup.exe (Cygwin package manager) then trying downloading 64bit version of this setup. Worked for me.

Compare object instances for equality by their attributes

Implement the __eq__ method in your class; something like this:

def __eq__(self, other):
    return self.path == other.path and self.title == other.title

Edit: if you want your objects to compare equal if and only if they have equal instance dictionaries:

def __eq__(self, other):
    return self.__dict__ == other.__dict__

how to make twitter bootstrap submenu to open on the left side?

Actually - if you are ok with floating the dropdown wrapper - I've found it to be as easy as to add navbar-right to the dropdown.

This seems like cheating, since it's not in a navbar, but it works fine for me.

<div class="dropdown navbar-right">
...
</div>

You can then further customize the floating with a pull-left directly in the dropdown...

<div class="dropdown pull-left navbar-right">
...
</div>

... or as a wrapper around it ...

<div class="pull-left">
  <div class="dropdown navbar-right">
  ...
  </div>
</div>

How to get time (hour, minute, second) in Swift 3 using NSDate?

For best useful I create this function:

func dateFormatting() -> String {
    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE dd MMMM yyyy - HH:mm:ss"//"EE" to get short style
    let mydt = dateFormatter.string(from: date).capitalized

    return "\(mydt)"
}

You simply call it wherever you want like this:

print("Date = \(self.dateFormatting())")

this is the Output:

Date = Monday 15 October 2018 - 17:26:29

if want only the time simply change :

dateFormatter.dateFormat  = "HH:mm:ss"

and this is the output:

Date = 17:27:30

and that's it...

Binding value to style

Turns out the binding of style to a string doesn't work. The solution would be to bind the background of the style.

 <div class="circle" [style.background]="color">

While loop in batch

I have a trick for doing this!

I came up with this method because while on the CLI, it's not possible to use the methods provided in the other answers here and it had always bugged me.

I call this the "Do Until Break" or "Infinite" Loop:

Basic Example

FOR /L %L IN (0,0,1) DO @(
 ECHO. Counter always 0, See "%L" = "0" - Waiting a split second&ping -n 1 127.0.0.1>NUL )

This is truly an infinite loop!

This is useful for monitoring something in a CMD window, and allows you to use CTRL+C to break it when you're done.

Want to Have a counter?

Either use SET /A OR You can modify the FOR /L Loop to do the counting and still be infinite (Note, BOTH of these methods have a 32bit integer overflow)

SET /A Method:

FOR /L %L IN (0,0,1) DO @(
 SET /A "#+=1"&ECHO. L Still equals 0, See "%L = 0"!  - Waiting a split second &ping -n 1 127.0.0.1>NUL  )

Native FOR /L Counter:

FOR /L %L IN (-2147483648,1,2147483648) DO @(
 ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL  )

Counting Sets of 4294967295 and Showing Current Value of L:

FOR /L %L IN (1,1,2147483648) DO @(
 (
  IF %L EQU 0 SET /A "#+=1">NUL
 )&SET /A "#+=0"&ECHO. Sets of 4294967295 - Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL )

However, what if:

  • You're interested in reviewing the output of the monitor, and concerned that I will pass the 9999 line buffer limit before I check it after it has completed.
  • You'd like to take some additional actions once the Thing I am monitoring is finished.

For this, I determined how to use a couple methods to break the FOR Loop prematurely effectively turning it into a "DO WHILE" or "DO UNTIL" Loop, which is otherwise sorely lacking in CMD.

NOTE: Most of the time a loop will continue to iterate past the condition you checked for, often this is a wanted behavior, but not in our case.

Turn the "infinite Loop" into a "DO WHILE" / "DO UNTIL" Loop

UPDATE: Due to wanting to use this code in CMD Scripts (and have them persist!) as well as CLI, and on thinking if there might be a "more Correct" method to achieve this I recommend using the New method!

New Method (Can be used inside CMD Scripts without exiting the script):

FOR /F %%A IN ('
  CMD /C "FOR /L %%L IN (0,1,2147483648) DO @( ECHO.%%L & IF /I %%L EQU 10 ( exit /b  ) )"
') DO @(
  ECHO %%~A
)

At CLI:

FOR /F %A IN ('
  CMD /C "FOR /L %L IN (0,1,2147483648) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b  ) )"
') DO @(
  ECHO %~A
)

Original Method (Will work on CLI just fine, but will kill a script.)

FOR /L %L IN (0,1,2147483648) DO @(
  ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL&(
    IF /I %L EQU 10 (
      ECHO.Breaking the Loop! Because We have matched the condition!&DIR >&0
    )
  )
) 2>NUL

Older Post Stuff

Through chance I had hit upon some ways to exit loops prematurely that did not close the CMD prompt when trying to do other things which gave me this Idea.

NOTE:

While ECHO.>&3 >NUL had worked for me in some scenarios, I have played with this off and on over the years and found that DIR >&0 >NUL was much more consistent.

I am re-writing this answer from here forward to use that method instead as I recently found the old note to myself to use this method instead.

Edited Post with better Method Follows:

DIR >&0 >NUL

The >NUL is optional, I just prefer not to have it output the error.

I prefer to match inLine when possible, as you can see in this sanitized example of a Command I use to monitor LUN Migrations on our VNX.

for /l %L IN (0,0,1) DO @(
   ECHO.& ECHO.===========================================& (
     [VNX CMD] | FINDSTR /R /C:"Source LU Name" /C:"State:" /C:"Time " || DIR >&0 >NUL
   ) & Ping -n 10 1.1.1.1 -w 1000>NUL )

Also, I have another method I found in that note to myself which I just re-tested to confirm works just as well at the CLI as the other method.

Apparently, when I first posted here I posted an older iteration I was playing with instead of the two newer ones which work better:

In this method, we use EXIT /B to exit the For Loop, but we don't want to exit the CLI so we wrap it in a CMD session:

FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b  ) )" ') DO @(ECHO %~A)

Because the loop itself happens in the CMD session, we can use EXIT /B to exit the iteration of the loop without losing our CMD Session, and without waiting for the loop to complete, much the same as with the other method.

I would go so far as to say that this method is likely the "intended" method for the sort of scenario where you want to break a for loop at the CLI, as using CMD session is also the only way to get Delayed expansion working at the CLI for your loops, and the behavior and such behavior is clearly an intended workflow to leave a CMD session.

IE: Microsoft clearly made an intentional effort to have CMD Exit /B For loops behave this way, while the "Intended" way of doing this, as my other method, relies on having accidentally created just the right error to kick you out of the loop without letting the loop finish processing, which I only happenstantially discovered, and seems to only reliably work when using the DIR command which is fairly strange.

So that said, I think it's probably a better practice to use Method 2:

FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b  ) )" ') DO @(ECHO %~A)

Although I suspect Method 1 is going to be slightly faster:

FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( DIR >&) >NUL ) )

And in either case, both should allow DO-While loops as you need for your purposes.

Show whitespace characters in Visual Studio Code

The option to make whitespace visible now appears as an option on the View menu, as "Toggle Render Whitespace" in version 1.15.1 of Visual Studio Code.

How to know if a Fragment is Visible?

getUserVisibleHint() comes as true only when the fragment is on the view and visible

What does getActivity() mean?

I to had a similar doubt what I got to know was getActivity() returns the Activity to which the fragment is associated.

The getActivity() method is used generally in static fragment as the associated activity will not be static and non static member cannot be used in static member.

I used <code>getActivity()</code> here to get non-static activity to which the the placeholder fragment is associated.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

How to force a script reload and re-execute?

Here's a method which is similar to Kelly's but will remove any pre-existing script with the same source, and uses jQuery.

<script>
    function reload_js(src) {
        $('script[src="' + src + '"]').remove();
        $('<script>').attr('src', src).appendTo('head');
    }
    reload_js('source_file.js');
</script>

Note that the 'type' attribute is no longer needed for scripts as of HTML5. (http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#the-script-element)

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

You can subclass HandleErrorAttribute and override its OnException member (no need to copy) so that it logs the exception with ELMAH and only if the base implementation handles it. The minimal amount of code you need is as follows:

using System.Web.Mvc;
using Elmah;

public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);
        if (!context.ExceptionHandled) 
            return;
        var httpContext = context.HttpContext.ApplicationInstance.Context;
        var signal = ErrorSignal.FromContext(httpContext);
        signal.Raise(context.Exception, httpContext);
    }
}

The base implementation is invoked first, giving it a chance to mark the exception as being handled. Only then is the exception signaled. The above code is simple and may cause issues if used in an environment where the HttpContext may not be available, such as testing. As a result, you will want code that is that is more defensive (at the cost of being slightly longer):

using System.Web;
using System.Web.Mvc;
using Elmah;

public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);
        if (!context.ExceptionHandled       // if unhandled, will be logged anyhow
            || TryRaiseErrorSignal(context) // prefer signaling, if possible
            || IsFiltered(context))         // filtered?
            return;

        LogException(context);
    }

    private static bool TryRaiseErrorSignal(ExceptionContext context)
    {
        var httpContext = GetHttpContextImpl(context.HttpContext);
        if (httpContext == null)
            return false;
        var signal = ErrorSignal.FromContext(httpContext);
        if (signal == null)
            return false;
        signal.Raise(context.Exception, httpContext);
        return true;
    }

    private static bool IsFiltered(ExceptionContext context)
    {
        var config = context.HttpContext.GetSection("elmah/errorFilter")
                        as ErrorFilterConfiguration;

        if (config == null)
            return false;

        var testContext = new ErrorFilterModule.AssertionHelperContext(
                              context.Exception, 
                              GetHttpContextImpl(context.HttpContext));
        return config.Assertion.Test(testContext);
    }

    private static void LogException(ExceptionContext context)
    {
        var httpContext = GetHttpContextImpl(context.HttpContext);
        var error = new Error(context.Exception, httpContext);
        ErrorLog.GetDefault(httpContext).Log(error);
    }

    private static HttpContext GetHttpContextImpl(HttpContextBase context)
    {
        return context.ApplicationInstance.Context;
    }
}

This second version will try to use error signaling from ELMAH first, which involves the fully configured pipeline like logging, mailing, filtering and what have you. Failing that, it attempts to see whether the error should be filtered. If not, the error is simply logged. This implementation does not handle mail notifications. If the exception can be signaled then a mail will be sent if configured to do so.

You may also have to take care that if multiple HandleErrorAttribute instances are in effect then duplicate logging does not occur, but the above two examples should get your started.

Get the distance between two geo points

you can get distance and time using google Map API Google Map API

just pass downloaded JSON to this method you will get real time Distance and Time between two latlong's

void parseJSONForDurationAndKMS(String json) throws JSONException {

    Log.d(TAG, "called parseJSONForDurationAndKMS");
    JSONObject jsonObject = new JSONObject(json);
    String distance;
    String duration;
    distance = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text");
    duration = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text");

    Log.d(TAG, "distance : " + distance);
    Log.d(TAG, "duration : " + duration);

    distanceBWLats.setText("Distance : " + distance + "\n" + "Duration : " + duration);


}

Renaming column names of a DataFrame in Spark Scala

def aliasAllColumns(t: DataFrame, p: String = "", s: String = ""): DataFrame =
{
  t.select( t.columns.map { c => t.col(c).as( p + c + s) } : _* )
}

In case is isn't obvious, this adds a prefix and a suffix to each of the current column names. This can be useful when you have two tables with one or more columns having the same name, and you wish to join them but still be able to disambiguate the columns in the resultant table. It sure would be nice if there were a similar way to do this in "normal" SQL.

Sending cookies with postman

Enable intercepter in this way

Basically it is a chrome plug in. After installing the extention, you also need to make sure the extention is enabled from chrome side.

enter image description here

Asynchronous vs synchronous execution, what does it really mean?

In regards to the "at the same time" definition of synchronous execution (which is sometimes confusing), here's a good way to understand it:

Synchronous Execution: All tasks within a block of code are all executed at the same time.

Asynchronous Execution: All tasks within a block of code are not all executed at the same time.

how to delete all cookies of my website in php

I had to add the following to the top answer to actually remove a few cookies that wouldn't go away:

foreach($_COOKIE as $cook) {
    setcookie($cook, '', time()-1000);
    setcookie($cook, '', time()-1000, '/');
}

Create zip file and ignore directory structure

Use the -j option:

   -j     Store  just the name of a saved file (junk the path), and do not
          store directory names. By default, zip will store the full  path
          (relative to the current path).

Django CharField vs TextField

In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.

Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.

What is aria-label and how should I use it?

Prerequisite:

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type="edit" aria-label="search" placeholder="search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id="sd">Search</span>

<input type="text" aria-labelledby="sd">

Approach 2:

aria-labelledby can also be used to combine two labels for screen reader users

<span id="de">Billing Address</span>

<span id="sd">First Name</span>

<input type="text" aria-labelledby="de sd">

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

How to use radio buttons in ReactJS?

Clicking a radio button should trigger an event that either:

  1. calls setState, if you only want the selection knowledge to be local, or
  2. calls a callback that has been passed in from above self.props.selectionChanged(...)

In the first case, the change is state will trigger a re-render and you can do
<td>chosen site name {this.state.chosenSiteName} </td>

in the second case, the source of the callback will update things to ensure that down the line, your SearchResult instance will have chosenSiteName and chosenAddress set in it's props.

How do I sort a table in Excel if it has cell references in it?

I had this same problem; I had a master sheet which was a summary of information on other worksheets in my workbook.

If you just want to filter/sort in a worksheet where you have your data stored, and then return it to its original state (no matter what you are filtering/sorting by) just make your first column a Line Item Number.

After your initial filter/sort you can then just resort by the “Line Item Number” to return everything back to normal. NOTE: This only works if you always add new rows to the end of the list in sequence.

Best way to implement keyboard shortcuts in a Windows Forms application?

You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == (Keys.Control | Keys.F)) {
    MessageBox.Show("What the Ctrl+F?");
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}

How to repeat last command in python interpreter shell?

For repeating the last command in python, you can use <Alt + n> in windows

Is there a float input type in HTML5?

This topic (e.g. step="0.01") relates to stepMismatch and is supported by all browsers as follows: enter image description here

Tomcat 8 is not able to handle get request with '|' in query parameters?

Since Tomcat 7.0.76, 8.0.42, 8.5.12 you can define property requestTargetAllow to allow forbiden characters.

Add this line in your catalina.properties

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

Socket send and receive byte array

You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.

This is the easiest case for a known size (100 bytes):

in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);

In this case DataInputStream makes sense as it offers readFully(). If you don't use it, you need to loop yourself until the expected number of bytes is read.

How to have multiple CSS transitions on an element?

Something like the following will allow for multiple transitions simultaneously:

-webkit-transition: color .2s linear, text-shadow .2s linear;
   -moz-transition: color .2s linear, text-shadow .2s linear;
     -o-transition: color .2s linear, text-shadow .2s linear;
        transition: color .2s linear, text-shadow .2s linear;

Example: http://jsbin.com/omogaf/2

Calculate mean and standard deviation from a vector of samples in C++ using Boost

Improving on the answer by musiphil, you can write a standard deviation function without the temporary vector diff, just using a single inner_product call with the C++11 lambda capabilities:

double stddev(std::vector<double> const & func)
{
    double mean = std::accumulate(func.begin(), func.end(), 0.0) / func.size();
    double sq_sum = std::inner_product(func.begin(), func.end(), func.begin(), 0.0,
        [](double const & x, double const & y) { return x + y; },
        [mean](double const & x, double const & y) { return (x - mean)*(y - mean); });
    return std::sqrt(sq_sum / func.size());
}

I suspect doing the subtraction multiple times is cheaper than using up additional intermediate storage, and I think it is more readable, but I haven't tested the performance yet.

How to use moment.js library in angular 2 typescript app?

with ng CLI

> npm install moment --save

in app.module

import * as moment from 'moment';

providers: [{ provide: 'moment', useValue: moment }]

in component

constructor(@Inject('moment') private moment)

this way you import moment once

UPDATE Angular => 5

{
   provide: 'moment', useFactory: (): any => moment
}

For me works in prod with aot and also with universal

I dont like using any but using moment.Moment I got

Error   Typescript  Type 'typeof moment' is not assignable to type 'Moment'. Property 'format' is missing in type 'typeof moment'.

displayname attribute vs display attribute

Perhaps this is specific to .net core, I found DisplayName would not work but Display(Name=...) does. This may save someone else the troubleshooting involved :)

//using statements
using System;
using System.ComponentModel.DataAnnotations;  //needed for Display annotation
using System.ComponentModel;  //needed for DisplayName annotation

public class Whatever
{
    //Property
    [Display(Name ="Release Date")]
    public DateTime ReleaseDate { get; set; }
}


//cshtml file
@Html.DisplayNameFor(model => model.ReleaseDate)

ImportError: No Module named simplejson

For anyone coming across this years later:

TL;DR check your pip version (2 vs 3)

I had this same issue and it was not fixed by running pip install simplejson despite pip insisting that it was installed. Then I realized that I had both python 2 and python 3 installed.

> python -V
Python 2.7.12
> pip -V
pip 9.0.1 from /usr/local/lib/python3.5/site-packages (python 3.5)

Installing with the correct version of pip is as easy as using pip2:

> pip2 install simplejson

and then python 2 can import simplejson fine.

I want to align the text in a <td> to the top

you can use valign="top" on the td tag it is working perfectly for me.

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

getTimezoneOffset() returns the opposite sign of the format required by the spec that you referenced.

This format is also known as ISO8601, or more precisely as RFC3339.

In this format, UTC is represented with a Z while all other formats are represented by an offset from UTC. The meaning is the same as JavaScript's, but the order of subtraction is inverted, so the result carries the opposite sign.

Also, there is no method on the native Date object called format, so your function in #1 will fail unless you are using a library to achieve this. Refer to this documentation.

If you are seeking a library that can work with this format directly, I recommend trying moment.js. In fact, this is the default format, so you can simply do this:

var m = moment();    // get "now" as a moment
var s = m.format();  // the ISO format is the default so no parameters are needed

// sample output:   2013-07-01T17:55:13-07:00

This is a well-tested, cross-browser solution, and has many other useful features.

How to clear Route Caching on server: Laravel 5.2.37

For your case solution is :

php artisan cache:clear
php artisan route:cache

Optimizing Route Loading is a must on production :

If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:

php artisan route:cache

This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.

Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.

Laravel 5 clear cache from route, view, config and all cache data from application

I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.

Reoptimized class loader:

php artisan optimize

Clear Cache facade value:

php artisan cache:clear

Clear Route cache:

php artisan route:cache

Clear View cache:

php artisan view:clear

Clear Config cache:

php artisan config:cache

Loading context in Spring using web.xml

You can also load the context while defining the servlet itself (WebApplicationContext)

  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/*.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

rather than (ApplicationContext)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

or can do both together.

Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet etc)

Context loaded by ContextLoaderListener will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.

How to launch Safari and open URL from iOS app

Here's what I did:

  1. I created an IBAction in the header .h files as follows:

    - (IBAction)openDaleDietrichDotCom:(id)sender;
    
  2. I added a UIButton on the Settings page containing the text that I want to link to.

  3. I connected the button to IBAction in File Owner appropriately.

  4. Then implement the following:

Objective-C

- (IBAction)openDaleDietrichDotCom:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.daledietrich.com"]];
}

Swift

(IBAction in viewController, rather than header file)

if let link = URL(string: "https://yoursite.com") {
  UIApplication.shared.open(link)
}

Accessing the logged-in user in a template

For symfony 2.6 and above we can use

{{ app.user.getFirstname() }}

as app.security global variable for Twig template has been deprecated and will be removed from 3.0

more info:

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

and see the global variables in

http://symfony.com/doc/current/reference/twig_reference.html

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

How to create a numpy array of arbitrary length strings?

You can do so by creating an array of dtype=object. If you try to assign a long string to a normal numpy array, it truncates the string:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'], 
      dtype='|S6')

But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)

Indeed, because it's an array of objects, you can assign any kind of python object to the array:

>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)

However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:

>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

Content Security Policy: The page's settings blocked the loading of a resource

You can disable them in your browser.

Firefox

Type about:config in the Firefox address bar and find security.csp.enable and set it to false.

Chrome

You can install the extension called Disable Content-Security-Policy to disable CSP.

Laravel - Return json along with http status code

You can use http_response_code() to set HTTP response code.

If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code.

http_response_code(201); // Set response status code to 201

For Laravel(Reference from: https://stackoverflow.com/a/14717895/2025923):

return Response::json([
    'hello' => $value
], 201); // Status code here

When to use a linked list over an array/array list?

It all depends what type of operation you are doing while iterating , all data structures have trade off between time and memory and depending on our needs we should choose the right DS. So there are some cases where LinkedList are faster then array and vice versa . Consider the three basic operation on data structures.

  • Searching

Since array is index based data structure searching array.get(index) will take O(1) time while linkedlist is not index DS so you will need to traverse up to index , where index <=n , n is size of linked list , so array is faster the linked list when have random access of elements.

Q.So what's the beauty behind this ?

As Arrays are contiguous memory blocks, large chunks of them will be loaded into the cache upon first access this makes it comparatively quick to access remaining elements of the array,as much as we access the elements in array locality of reference also increases thus less catch misses, Cache locality refers to the operations being in the cache and thus execute much faster as compared to in memory,basically In array we maximize the chances of sequential element access being in the cache. While Linked lists aren't necessarily in contiguous blocks of memory, there's no guarantee that items which appear sequentially in the list are actually arranged near each-other in memory, this means fewer cache hits e.g. more cache misses because we need to read from memory for every access of linked list element which increases the time it takes to access them and degraded performance so if we are doing more random access operation aka searching , array will be fast as explained below.

  • Insertion

This is easy and fast in LinkedList as insertion is O(1) operation in LinkedList (in Java) as compared to array, consider the case when array is full, we need to copy contents to new array if array gets full which makes inserting an element into ArrayList of O(n) in worst case, while ArrayList also needs to update its index if you insert something anywhere except at the end of array , in case of linked list we needn't to be resize it, you just need to update pointers.

  • Deletion

It works like insertions and better in LinkedList than array.

Log4net rolling daily filename with date in the file name

I've tried all the answers, but there was always something missing and not functioning as expected for me.

Then I experimented a bit with the hints given in each answer and was successful with the following setting:

<appender name="RollingActivityLog" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="C:\temp\LOG4NET_Sample_Activity.log" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <staticLogFileName value="false" />
  <preserveLogFileNameExtension value="true" />
  <datePattern value="-yyyyMMdd" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %-5level - %message%newline" />
  </layout>
</appender>

The issue with other combinations of parameters was that the latest file didn't have the time pattern, or that the time pattern was appended as .log20171215 which created a new file time (and a new file type!) each day - or both issues appeared.

Now with this setting you are getting files like this one:

LOG4NET_Sample_Activity-20171215.log

which is what I wanted.


To summarize:

  • Don't put the date pattern in the <file value=... attribute, just define it in the datePattern.

  • Make sure you have the preserveLogFileNameExtension value attribute set to true.

  • Make sure you have the staticLogFileName value set to false.

  • Set the rollingStyle attribute value to Date.

How do I speed up the gwt compiler?

You can add one option to your build for production:

-localWorkers 8 – Where 8 is the number of concurrent threads that calculate permutations. All you have to do is to adjust this number to the number that is more convenient to you. See GWT compilation performance (thanks to Dennis Ich comment).

If you are compiling to the testing environment, you can also use:

-draftCompile which enables faster, but less-optimized compilations

-optimize 0 which does not optimize your code (9 is the max optimization value)

Another thing that more than doubled the build and hosted mode performance was the use of an SSD disk (now hostedmode works like a charm). It's not an cheap solution, but depending on how much you use GWT and the cost of your time, it may worth it!

Hope this helps you!

UIView touch event in controller

Swift 4 / 5:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Swift 3:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

How can I use regex to get all the characters after a specific character, e.g. comma (",")

[^,]*$

might do. (Matches everything after the last comma).

Explanation: [^,] matches every character except for ,. The * denotes that the regexp matches any number of repetition of [^,]. The $ sign matches the end of the line.

Differences between "BEGIN RSA PRIVATE KEY" and "BEGIN PRIVATE KEY"

See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).

BEGIN RSA PRIVATE KEY is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY is PKCS#8 and indicates that the key type is included in the key data itself. From the link:

The unencrypted PKCS#8 encoded data starts and ends with the tags:

-----BEGIN PRIVATE KEY-----
BASE64 ENCODED DATA
-----END PRIVATE KEY-----

Within the base64 encoded data the following DER structure is present:

PrivateKeyInfo ::= SEQUENCE {
  version         Version,
  algorithm       AlgorithmIdentifier,
  PrivateKey      BIT STRING
}

AlgorithmIdentifier ::= SEQUENCE {
  algorithm       OBJECT IDENTIFIER,
  parameters      ANY DEFINED BY algorithm OPTIONAL
}

So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.

As opposed to BEGIN RSA PRIVATE KEY, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY is PKCS#1:

RSA Private Key file (PKCS#1)

The RSA private key PEM file is specific for RSA keys.

It starts and ends with the tags:

-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----

Within the base64 encoded data the following DER structure is present:

RSAPrivateKey ::= SEQUENCE {
  version           Version,
  modulus           INTEGER,  -- n
  publicExponent    INTEGER,  -- e
  privateExponent   INTEGER,  -- d
  prime1            INTEGER,  -- p
  prime2            INTEGER,  -- q
  exponent1         INTEGER,  -- d mod (p-1)
  exponent2         INTEGER,  -- d mod (q-1)
  coefficient       INTEGER,  -- (inverse of q) mod p
  otherPrimeInfos   OtherPrimeInfos OPTIONAL
}

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

Proper MIME type for OTF fonts

Ignore the chrome warning. There is no standard MIME type for OTF fonts.

font/opentype may silence the warning, but that doesn't make it the "right" thing to do.

Arguably, you're better off making one up, e.g. with "application/x-opentype" because at least "application" is a registered content type, while "font" is not.

Update: OTF remains a problem, but WOFF grew an IANA MIME type of application/font-woff in January 2013.

Update 2: OTF has grown a MIME type: application/font-sfnt In March 2013. This type also applies to .ttf

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

Correctly ignore all files recursively under a specific folder except for a specific file type

This might look stupid, but check if you haven't already added the folder/files you are trying to ignore to the index before. If you did, it does not matter what you put in your .gitignore file, the folders/files will still be staged.

Reorder / reset auto increment primary key

You can also simply avoid using numeric IDs as Primary Key. You could use Country codes as primary id if the table holds countries information, or you could use permalinks, if it hold articles for example.

You could also simply use a random, or an MD5 value. All this options have it's own benefits, specially on IT sec. numeric IDs are easy to enumerate.

Transparent background in JPEG image

JPEG can't support transparency because it uses RGB color space. If you want transparency use a format that supports alpha values. Example PNG is an image format that uses RGBA color space where (r = red, g = green, b = blue, a = alpha value). Alpha value is used as an opacity measure, 0% is fully transparent and 100% is completely opaque. pixel.

Why do we assign a parent reference to the child object in Java?

I know this is a very old thread but I came across the same doubt once.

So the concept of Parent parent = new Child(); has something to do with early and late binding in java.

The binding of private, static and final methods happen at the compile as they cannot be overridden and the normal method calls and overloaded methods are example of early binding.

Consider the example:

class Vehicle
{
    int value = 100;
    void start() {
        System.out.println("Vehicle Started");
    }

    static void stop() {
        System.out.println("Vehicle Stopped");
    }
}

class Car extends Vehicle {

    int value = 1000;

    @Override
    void start() {
        System.out.println("Car Started");
    }

    static void stop() {
        System.out.println("Car Stopped");
    }

    public static void main(String args[]) {

        // Car extends Vehicle
        Vehicle vehicle = new Car();
        System.out.println(vehicle.value);
        vehicle.start();
        vehicle.stop();
    }
}

Output: 100

Car Started

Vehicle Stopped

This is happening because stop() is a static method and cannot be overridden. So binding of stop() happens at compile time and start() is non-static is being overridden in child class. So, the information about type of object is available at the run time only(late binding) and hence the start() method of Car class is called.

Also in this code the vehicle.value gives us 100 as the output because variable initialization doesn't come under late binding. Method overriding is one of the ways in which java supports run time polymorphism.

  • When an overridden method is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time.
  • At run-time, it depends on the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed

I hope this answers where Parent parent = new Child(); is important and also why you weren't able to access the child class variable using the above reference.

How to set entire application in portrait mode only?

Yes you can do this both programmatically and for all your activities making an AbstractActivity that all your activities extends.

public abstract class AbstractActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

This abstract activity can also be used for a global menu.

What is the difference between atan and atan2 in C++?

With atan2 you can determine the quadrant as stated here.

You can use atan2 if you need to determine the quadrant.

How can I remove an SSH key?

Note that there are at least two bug reports for ssh-add -d/-D not removing keys:

The exact issue is:

ssh-add -d/-D deletes only manually added keys from gnome-keyring.
There is no way to delete automatically added keys.
This is the original bug, and it's still definitely present.

So, for example, if you have two different automatically-loaded ssh identities associated with two different GitHub accounts -- say for work and for home -- there's no way to switch between them. GitHubtakes the first one which matches, so you always appear as your 'home' user to GitHub, with no way to upload things to work projects.

Allowing ssh-add -d to apply to automatically-loaded keys (and ssh-add -t X to change the lifetime of automatically-loaded keys), would restore the behavior most users expect.


More precisely, about the issue:

The culprit is gpg-keyring-daemon:

  • It subverts the normal operation of ssh-agent, mostly just so that it can pop up a pretty box into which you can type the passphrase for an encrypted ssh key.
  • And it paws through your .ssh directory, and automatically adds any keys it finds to your agent.
  • And it won't let you delete those keys.

How do we hate this? Let's not count the ways -- life's too short.

The failure is compounded because newer ssh clients automatically try all the keys in your ssh-agent when connecting to a host.
If there are too many, the server will reject the connection.
And since gnome-keyring-daemon has decided for itself how many keys you want your ssh-agent to have, and has autoloaded them, AND WON'T LET YOU DELETE THEM, you're toast.

This bug is still confirmed in Ubuntu 14.04.4, as recently as two days ago (August 21st, 2014)


A possible workaround:

  • Do ssh-add -D to delete all your manually added keys. This also locks the automatically added keys, but is not much use since gnome-keyring will ask you to unlock them anyways when you try doing a git push.
  • Navigate to your ~/.ssh folder and move all your key files except the one you want to identify with into a separate folder called backup. If necessary you can also open seahorse and delete the keys from there.
  • Now you should be able to do git push without a problem.

Another workaround:

What you really want to do is to turn off gpg-keyring-daemon altogether.
Go to System --> Preferences --> Startup Applications, and unselect the "SSH Key Agent (Gnome Keyring SSH Agent)" box -- you'll need to scroll down to find it.

You'll still get an ssh-agent, only now it will behave sanely: no keys autoloaded, you run ssh-add to add them, and if you want to delete keys, you can. Imagine that.

This comments actually suggests:

The solution is to keep gnome-keyring-manager from ever starting up, which was strangely difficult by finally achieved by removing the program file's execute permission.


Ryan Lue adds another interesting corner case in the comments:

In case this helps anyone: I even tried deleting the id_rsa and id_rsa.pub files altogether, and the key was still showing up.

Turns out gpg-agent was caching them in a ~/.gnupg/sshcontrol file; I had to manually delete them from there.

That is the case when the keygrip has been added as in here.

How to make URL/Phone-clickable UILabel?

Swift 4.0 possible solution using UIButton

     phoneButton = UIButton(frame: CGRect(x: view.frame.width * 0, y: view.frame.height * 0.1, width: view.frame.width * 1, height: view.frame.height * 0.05))
     phoneButton.setTitle("333-333-3333", for: .normal )
     phoneButton.setTitleColor(UIColor(red: 0 / 255, green: 0 / 255, blue: 238 / 255, alpha: 1.0), for: .normal)
     phoneButton.addTarget(self, action: #selector(self.callPhone), for: .touchUpInside )

     @objc func callPhone(){

         UIApplication.shared.open(URL(string:"tel://3333333333")!, options: [:] , completionHandler: nil)


    }

What’s the best way to get an HTTP response code from a URL?

Addressing @Niklas R's comment to @nickanor's answer:

from urllib.error import HTTPError
import urllib.request

def getResponseCode(url):
    try:
        conn = urllib.request.urlopen(url)
        return conn.getcode()
    except HTTPError as e:
        return e.code

Disabling Controls in Bootstrap

No, Bootstrap does not introduce special considerations for disabling a drop-down.

<select id="xxx" name="xxx" class="input-medium" disabled>

or

<select id="xxx" name="xxx" class="input-medium" disabled="disabled">

will work. I prefer to give attributes values (as in the second form; in XHTML, attributes must have a value), but the HTML spec says:

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

(from http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#boolean-attribute)

The key differences between read-only and disabled:*

The Disabled attribute

  • Values for disabled form elements are not passed to the processor method. The W3C calls this a successful element.(This works similar to form check boxes that are not checked.)
  • Some browsers may override or provide default styling for disabled form elements. (Gray out or emboss text) Internet Explorer 5.5 is particularly nasty about this.
  • Disabled form elements do not receive focus.
  • Disabled form elements are skipped in tabbing navigation.

The Read Only Attribute

  • Not all form elements have a readonly attribute. Most notable, the <SELECT>, <OPTION>, and <BUTTON> elements do not have readonly attributes (although thy both have disabled attributes)
  • Browsers provide no default overridden visual feedback that the form element is read only
  • Form elements with the readonly attribute set will get passed to the form processor.
  • Read only form elements can receive the focus
  • Read only form elements are included in tabbed navigation.

*-blatant plagiarism from http://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/

How do I get the IP address into a batch-file variable?

try something like this

echo "yours ip addresses are:"
ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1

linux like systems

Difference between long and int data types

A typical best practice is not using long/int/short directly. Instead, according to specification of compilers and OS, wrap them into a header file to ensure they hold exactly the amount of bits that you want. Then use int8/int16/int32 instead of long/int/short. For example, on 32bit Linux, you could define a header like this

typedef char int8;
typedef short int16;
typedef int int32;
typedef unsigned int uint32;

VMware Workstation and Device/Credential Guard are not compatible

I don't know why but version 3.6 of DG_Readiness_Tool didn't work for me. After I restarted my laptop problem still persisted. I was looking for solution and finally I came across version 3.7 of the tool and this time problem went away. Here you can find latest powershell script:

DG_Readiness_Tool_v3.7

TypeError: 'builtin_function_or_method' object is not subscriptable

Mad a similar error, easy to fix:

    TypeError Traceback (most recent call last) <ipython-input-2-1eb12bfdc7db> in <module>
  3 mylist = [10,20,30] ----> 4 arr = np.array[(10,20,30)] 5 d = {'a':10, 'b':20, 'c':30} TypeError: 'builtin_function_or_method' object is not subscriptable

but I should have written it as:

arr = np.array([10,20,30])

Very fixable, rookie/dumb mistake.

Action Image MVC3 Razor

You can create an extension method for HtmlHelper to simplify the code in your CSHTML file. You could replace your tags with a method like this:

// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")

Here is a sample extension method for the code above:

// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
{
    var url = new UrlHelper(html.ViewContext.RequestContext);

    // build the <img> tag
    var imgBuilder = new TagBuilder("img");
    imgBuilder.MergeAttribute("src", url.Content(imagePath));
    imgBuilder.MergeAttribute("alt", alt);
    string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

    // build the <a> tag
    var anchorBuilder = new TagBuilder("a");
    anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
    anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
    string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

    return MvcHtmlString.Create(anchorHtml);
}

Parallel foreach with asynchronous lambda

You can use the ParallelForEachAsync extension method from AsyncEnumerator NuGet Package:

using Dasync.Collections;

var bag = new ConcurrentBag<object>();
await myCollection.ParallelForEachAsync(async item =>
{
  // some pre stuff
  var response = await GetData(item);
  bag.Add(response);
  // some post stuff
}, maxDegreeOfParallelism: 10);
var count = bag.Count;

Random integer in VB.NET

Public Function RandomNumber(ByVal n As Integer) As Integer
    'initialize random number generator
    Dim r As New Random(System.DateTime.Now.Millisecond)
    Return r.Next(1, n)
End Function

Get user's non-truncated Active Directory groups from command line

Much easier way in PowerShell:

Get-ADPrincipalGroupMembership <username>

Requirement: the account you yourself are running under must be a member of the same domain as the target user, unless you specify -Credential and -Server (untested).

In addition, you must have the Active Directory Powershell module installed, which as @dave-lucre says in a comment to another answer, is not always an option.

For group names only, try one of these:

(Get-ADPrincipalGroupMembership <username>).Name
Get-ADPrincipalGroupMembership <username> |Select Name

How to Inspect Element using Safari Browser

In your Safari menu bar click Safari > Preferences & then select the Advanced tab.

Select: "Show Develop menu in menu bar"

Now you can click Develop in your menu bar and choose Show Web Inspector

You can also right-click and press "Inspect element".

How to place div side by side

<div class="container" style="width: 100%;">
    <div class="sidebar" style="width: 200px; float: left;">
        Sidebar
    </div>
    <div class="content" style="margin-left: 202px;">
        content 
    </div>
</div>

This will be cross browser compatible. Without the margin-left you will run into issues with content running all the way to the left if you content is longer than your sidebar.

IPython/Jupyter Problems saving notebook as PDF

2015-4-22: It looks like an IPython update means that --to pdf should be used instead of --to latex --post PDF. There is a related Github issue.

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

Display more Text in fullcalendar

as a possible solution: Add some extra more content to the title. Overwrite this css style:

 .fc-day-grid-event .fc-content {
   white-space: normal; 
}

Strip double quotes from a string in .NET

You can use either of these:

s = s.Replace(@"""","");
s = s.Replace("\"","");

...but I do get curious as to why you would want to do that? I thought it was good practice to keep attribute values quoted?

Extract subset of key-value pairs from Python dictionary object?

interesting_keys = ('l', 'm', 'n')
subdict = {x: bigdict[x] for x in interesting_keys if x in bigdict}

How do you make sure email you send programmatically is not automatically marked as spam?

First of all, you need to ensure the required email authentication mechanisms like SPF and DKIM are in place. These two are prominent ways of proving that you were the actual sender of an email and it's not really spoofed. This reduces the chances of emails getting filtered as spam.

Second thing is, you can check the reverse DNS output of your domain name against different DNSBLs. Use below simple command on terminal:

  **dig a +short (domain-name).(blacklist-domain-name)**

  ie.  dig a +short example.com.dsn.rfc-clueless.org
  > 127.0.0.2

In the above examples, this means your domain "example.com" is listed in blacklist but due to Domain Setting Compliance(rfc-clueless.org list domain which has compliance issue )

note: I prefer multivalley and pepipost tool for checking the domain listings.

The from address/reply-to-id should be proper, always use visible unsubscribe button within your email body (this will help your users to sign out from your email-list without killing your domain reputation)

How to change link color (Bootstrap)

I'm fully aware that the code in the original quesiton displays a situation of being navbar related. But as you also dive into other compontents, it maybe helpful to know that the class options for text styling may not work.

But you can still create your own helper classes to keep the "Bootstrap flow" going in your HTML. Here is one idea to help style links that are in panel-title regions.

The following code by itself will not style a warning color on your anchor link...

<div class="panel panel-default my-panel-styles"> 
...    
  <h4 class="panel-title">
    <a class="accordion-toggle btn-block text-warning" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
      My Panel title that is also a link
    </a>
  </h4>
 ...
 </div>

But you could extend the Bootstrap styling package by adding your own class with appropriate colors like this...

.my-panel-styles .text-muted {color:#777;}
.my-panel-styles .text-primary {color:#337ab7;}
.my-panel-styles .text-success {color:#d44950;}
.my-panel-styles .text-info {color:#31708f;}
.my-panel-styles .text-warning {color:#8a6d3b;}
.my-panel-styles .text-danger {color:#a94442;}

...Now you can continue building out your panel anchor links with the Bootstrap colors you want.

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

Android set height and width of Custom view programmatically

You can set height and width like this:

myGraphView.setLayoutParams(new LayoutParams(width, height));

How to secure MongoDB with username and password

Some of the answers are sending mixed signals between using --auth command line flag or setting config file property.

security:
  authorization: enabled

I would like to clarify that aspect. First of all, authentication credentials (ie user/password) in both cases has to be created by executing db.createUser query on the default admin database. Once credentials are obtained, there are two ways to enable authentication:

  1. Without a custom config file: This is when the former auth flag is applicable. Start mongod like: usr/bin/mongod --auth
  2. With a custom config file: This is when the latter configs has to be present in the custom config file.Start mongod like: usr/bin/mongod --config <config file path>

To connect to the mongo shell with authentication: mongo -u <user> -p <password> --authenticationDatabase admin

--authenticationDatabase here is the database name where the user was created. All other mongo commands like mongorestore, mongodump accept the additional options ie -u <user> -p <password> --authenticationDatabase admin

Refer to https://docs.mongodb.com/manual/tutorial/enable-authentication/ for details.

How do I check if a string contains another string in Swift?

// Search string exist in employee name finding.
var empName:NSString! = employeeDetails[filterKeyString] as NSString

Case sensitve search.
let rangeOfSearchString:NSRange! = empName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch)

// Not found.
if rangeOfSearchString.location != Foundation.NSNotFound
{
    // search string not found in employee name.
}
// Found
else
{
    // search string found in employee name.
}

How to iterate through table in Lua?

For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.

Examples:

ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}

notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable
1       AAA
2       BBB
3       CCC

ipairs + ipairsCompatable2
1       DDD
2       EEE
3       FFF

ipairs + ipairsCompatable3
1       this
2       does
3       work

ipairs + notIpairsCompatable

pairs + notIpairsCompatable
2       this
3       does
4       not

ipairs + notIpairsCompatable2

pairs + notIpairsCompatable2
2       this
5       doesnt
24      either

ipairs + kindofIpairsCompatable
1       1
2       2
3       3

pairs + kindofIpairsCompatable
1       1
2       2
3       3
5       5
cool    bro

How to do a logical OR operation for integer comparison in shell scripting?

If a bash script

If [[ $input -gt number  ||  $input  -lt number  ]]
then 
    echo .........
else
    echo .........

fi

exit

Bash: infinite sleep (infinite blocking)

I recently had a need to do this. I came up with the following function that will allow bash to sleep forever without calling any external program:

snore()
{
    local IFS
    [[ -n "${_snore_fd:-}" ]] || { exec {_snore_fd}<> <(:); } 2>/dev/null ||
    {
        # workaround for MacOS and similar systems
        local fifo
        fifo=$(mktemp -u)
        mkfifo -m 700 "$fifo"
        exec {_snore_fd}<>"$fifo"
        rm "$fifo"
    }
    read ${1:+-t "$1"} -u $_snore_fd || :
}

NOTE: I previously posted a version of this that would open and close the file descriptor each time, but I found that on some systems doing this hundreds of times a second would eventually lock up. Thus the new solution keeps the file descriptor between calls to the function. Bash will clean it up on exit anyway.

This can be called just like /bin/sleep, and it will sleep for the requested time. Called without parameters, it will hang forever.

snore 0.1  # sleeps for 0.1 seconds
snore 10   # sleeps for 10 seconds
snore      # sleeps forever

There's a writeup with excessive details on my blog here

How to return values in javascript

It's difficult to tell what you're actually trying to do and if this is what you really need but you might also use a callback:

function myFunction(value1,callback)
{
     //Do stuff and 

     if(typeof callback == 'function'){
        callback(somevalue2,somevalue3);
    }
}


myFunction("1", function(value2, value3){
    if(value2 && value3)
    {
    //Do some stuff
    }
});

jQuery 1.9 .live() is not a function

You can avoid refactoring your code by including the following JavaScript code

jQuery.fn.extend({
    live: function (event, callback) {
       if (this.selector) {
            jQuery(document).on(event, this.selector, callback);
        }
        return this;
    }
});

How to use environment variables in docker compose

The DOCKER solution:

It looks like docker-compose 1.5+ has enabled variables substitution: https://github.com/docker/compose/releases

The latest Docker Compose allows you to access environment variables from your compose file. So you can source your environment variables, then run Compose like so:

set -a
source .my-env
docker-compose up -d

Then you can reference the variables in docker-compose.yml using ${VARIABLE}, like so:

db:
  image: "postgres:${POSTGRES_VERSION}"

And here is more info from the docs, taken here: https://docs.docker.com/compose/compose-file/#variable-substitution

When you run docker-compose up with this configuration, Compose looks for the POSTGRES_VERSION environment variable in the shell and substitutes its value in. For this example, Compose resolves the image to postgres:9.3 before running the configuration.

If an environment variable is not set, Compose substitutes with an empty string. In the example above, if POSTGRES_VERSION is not set, the value for the image option is postgres:.

Both $VARIABLE and ${VARIABLE} syntax are supported. Extended shell-style features, such as ${VARIABLE-default} and ${VARIABLE/foo/bar}, are not supported.

If you need to put a literal dollar sign in a configuration value, use a double dollar sign ($$).

And I believe this feature was added in this pull request: https://github.com/docker/compose/pull/1765

The BASH solution:

I notice folks have issues with Docker's environment variables support. Instead of dealing with environment variables in Docker, let's go back to basics, like bash! Here is a more flexible method using a bash script and a .env file.

An example .env file:

EXAMPLE_URL=http://example.com
# Note that the variable below is commented out and will not be used:
# EXAMPLE_URL=http://example2.com 
SECRET_KEY=ABDFWEDFSADFWWEFSFSDFM

# You can even define the compose file in an env variable like so:
COMPOSE_CONFIG=my-compose-file.yml
# You can define other compose files, and just comment them out
# when not needed:
# COMPOSE_CONFIG=another-compose-file.yml

then run this bash script in the same directory, which should deploy everything properly:

#!/bin/bash

docker rm -f `docker ps -aq -f name=myproject_*`
set -a
source .env
cat ${COMPOSE_CONFIG} | envsubst | docker-compose -f - -p "myproject" up -d

Just reference your env variables in your compose file with the usual bash syntax (ie ${SECRET_KEY} to insert the SECRET_KEY from the .env file).

Note the COMPOSE_CONFIG is defined in my .env file and used in my bash script, but you can easily just replace {$COMPOSE_CONFIG} with the my-compose-file.yml in the bash script.

Also note that I labeled this deployment by naming all of my containers with the "myproject" prefix. You can use any name you want, but it helps identify your containers so you can easily reference them later. Assuming that your containers are stateless, as they should be, this script will quickly remove and redeploy your containers according to your .env file params and your compose YAML file.

Update Since this answer seems pretty popular, I wrote a blog post that describes my Docker deployment workflow in more depth: http://lukeswart.net/2016/03/lets-deploy-part-1/ This might be helpful when you add more complexity to a deployment configuration, like nginx configs, LetsEncrypt certs, and linked containers.

Kill a postgresql session/connection

I use the following rake task to override the Rails drop_database method.

lib/database.rake

require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLAdapter < AbstractAdapter
      def drop_database(name)
        raise "Nah, I won't drop the production database" if Rails.env.production?
        execute <<-SQL
          UPDATE pg_catalog.pg_database
          SET datallowconn=false WHERE datname='#{name}'
        SQL

        execute <<-SQL
          SELECT pg_terminate_backend(pg_stat_activity.pid)
          FROM pg_stat_activity
          WHERE pg_stat_activity.datname = '#{name}';
        SQL
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
      end
    end
  end
end

Edit: This is for Postgresql 9.2+

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Another option would be using flexbox.

While it's not supported by IE8 and IE9, you could consider:

  • Not minding about those old IE versions
  • Providing a fallback
  • Using a polyfill

Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    background-color: #4C4;_x000D_
    min-height: 50px;_x000D_
    width: 100%;_x000D_
}_x000D_
footer {_x000D_
    background-color: #4C4;_x000D_
    min-height: 30px;_x000D_
    width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

Your selector is missing a . and though you say you want to change the border-color - you're adding and removing a class that sets the background-color

Python integer division yields float

According to Python3 documentation,python when divided by integer,will generate float despite expected to be integer.

For exclusively printing integer,use floor division method. Floor division is rounding off zero and removing decimal point. Represented by //

Hence,instead of 2/2 ,use 2//2

You can also import division from __future__ irrespective of using python2 or python3.

Hope it helps!

Inline CSS styles in React: how to implement a:hover?

In regards to styled-components and react-router v4 you can do this:

import {NavLink} from 'react-router-dom'

const Link = styled(NavLink)`     
  background: blue;

  &:hover {
    color: white;
  }
`

...
<Clickable><Link to="/somewhere">somewhere</Link></Clickable>

Adjust width and height of iframe to fit with content in it

All solutions given thus far only account for a once off resize. You mention you want to be able to resize the iFrame after the contents are modified. In order to do this, you need to execute a function inside the iFrame (once the contents are changed, you need to fire an event to say that the contents have changed).

I was stuck with this for a while, as code inside the iFrame seemed limited to the DOM inside the iFrame (and couldn't edit the iFrame), and code executed outside the iFrame was stuck with the DOM outside the iFrame (and couldn't pick up an event coming from inside the iFrame).

The solution came from discovering (via assistance from a colleague) that jQuery can be told what DOM to use. In this case, the DOM of the parent window.

As such, code such as this does what you need (when run inside the iFrame) :

<script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery("#IDofControlFiringResizeEvent").click(function () {
            var frame = $('#IDofiframeInMainWindow', window.parent.document);
            var height = jQuery("#IDofContainerInsideiFrame").height();
            frame.height(height + 15);
        });
    });
</script>

How do I hide the bullets on my list for the sidebar?

its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

add this to your css

ul{
     list-style:none;
}